1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CommentDiagnostic.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
43#include "clang/Sema/SemaInternal.h"
44#include "clang/Sema/Template.h"
45#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/Triple.h"
47#include <algorithm>
48#include <cstring>
49#include <functional>
50
51using namespace clang;
52using namespace sema;
53
54Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 if (OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58 }
59
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61}
62
63namespace {
64
65class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66 public:
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68 bool AllowTemplates = false,
69 bool AllowNonTemplates = true)
70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72 WantExpressionKeywords = false;
73 WantCXXNamedCasts = false;
74 WantRemainingKeywords = false;
75 }
76
77 bool ValidateCandidate(const TypoCorrection &candidate) override {
78 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79 if (!AllowInvalidDecl && ND->isInvalidDecl())
80 return false;
81
82 if (getAsTypeTemplateDecl(ND))
83 return AllowTemplates;
84
85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86 if (!IsType)
87 return false;
88
89 if (AllowNonTemplates)
90 return true;
91
92 // An injected-class-name of a class template (specialization) is valid
93 // as a template or as a non-template.
94 if (AllowTemplates) {
95 auto *RD = dyn_cast<CXXRecordDecl>(ND);
96 if (!RD || !RD->isInjectedClassName())
97 return false;
98 RD = cast<CXXRecordDecl>(RD->getDeclContext());
99 return RD->getDescribedClassTemplate() ||
100 isa<ClassTemplateSpecializationDecl>(RD);
101 }
102
103 return false;
104 }
105
106 return !WantClassName && candidate.isKeyword();
107 }
108
109 std::unique_ptr<CorrectionCandidateCallback> clone() override {
110 return llvm::make_unique<TypeNameValidatorCCC>(*this);
111 }
112
113 private:
114 bool AllowInvalidDecl;
115 bool WantClassName;
116 bool AllowTemplates;
117 bool AllowNonTemplates;
118};
119
120} // end anonymous namespace
121
122/// Determine whether the token kind starts a simple-type-specifier.
123bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124 switch (Kind) {
125 // FIXME: Take into account the current language when deciding whether a
126 // token kind is a valid type specifier
127 case tok::kw_short:
128 case tok::kw_long:
129 case tok::kw___int64:
130 case tok::kw___int128:
131 case tok::kw_signed:
132 case tok::kw_unsigned:
133 case tok::kw_void:
134 case tok::kw_char:
135 case tok::kw_int:
136 case tok::kw_half:
137 case tok::kw_float:
138 case tok::kw_double:
139 case tok::kw__Float16:
140 case tok::kw___float128:
141 case tok::kw_wchar_t:
142 case tok::kw_bool:
143 case tok::kw___underlying_type:
144 case tok::kw___auto_type:
145 return true;
146
147 case tok::annot_typename:
148 case tok::kw_char16_t:
149 case tok::kw_char32_t:
150 case tok::kw_typeof:
151 case tok::annot_decltype:
152 case tok::kw_decltype:
153 return getLangOpts().CPlusPlus;
154
155 case tok::kw_char8_t:
156 return getLangOpts().Char8;
157
158 default:
159 break;
160 }
161
162 return false;
163}
164
165namespace {
166enum class UnqualifiedTypeNameLookupResult {
167 NotFound,
168 FoundNonType,
169 FoundType
170};
171} // end anonymous namespace
172
173/// Tries to perform unqualified lookup of the type decls in bases for
174/// dependent class.
175/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176/// type decl, \a FoundType if only type decls are found.
177static UnqualifiedTypeNameLookupResult
178lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179 SourceLocation NameLoc,
180 const CXXRecordDecl *RD) {
181 if (!RD->hasDefinition())
182 return UnqualifiedTypeNameLookupResult::NotFound;
183 // Look for type decls in base classes.
184 UnqualifiedTypeNameLookupResult FoundTypeDecl =
185 UnqualifiedTypeNameLookupResult::NotFound;
186 for (const auto &Base : RD->bases()) {
187 const CXXRecordDecl *BaseRD = nullptr;
188 if (auto *BaseTT = Base.getType()->getAs<TagType>())
189 BaseRD = BaseTT->getAsCXXRecordDecl();
190 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191 // Look for type decls in dependent base classes that have known primary
192 // templates.
193 if (!TST || !TST->isDependentType())
194 continue;
195 auto *TD = TST->getTemplateName().getAsTemplateDecl();
196 if (!TD)
197 continue;
198 if (auto *BasePrimaryTemplate =
199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201 BaseRD = BasePrimaryTemplate;
202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203 if (const ClassTemplatePartialSpecializationDecl *PS =
204 CTD->findPartialSpecialization(Base.getType()))
205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206 BaseRD = PS;
207 }
208 }
209 }
210 if (BaseRD) {
211 for (NamedDecl *ND : BaseRD->lookup(&II)) {
212 if (!isa<TypeDecl>(ND))
213 return UnqualifiedTypeNameLookupResult::FoundNonType;
214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 }
216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218 case UnqualifiedTypeNameLookupResult::FoundNonType:
219 return UnqualifiedTypeNameLookupResult::FoundNonType;
220 case UnqualifiedTypeNameLookupResult::FoundType:
221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222 break;
223 case UnqualifiedTypeNameLookupResult::NotFound:
224 break;
225 }
226 }
227 }
228 }
229
230 return FoundTypeDecl;
231}
232
233static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234 const IdentifierInfo &II,
235 SourceLocation NameLoc) {
236 // Lookup in the parent class template context, if any.
237 const CXXRecordDecl *RD = nullptr;
238 UnqualifiedTypeNameLookupResult FoundTypeDecl =
239 UnqualifiedTypeNameLookupResult::NotFound;
240 for (DeclContext *DC = S.CurContext;
241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242 DC = DC->getParent()) {
243 // Look for type decls in dependent base classes that have known primary
244 // templates.
245 RD = dyn_cast<CXXRecordDecl>(DC);
246 if (RD && RD->getDescribedClassTemplate())
247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248 }
249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250 return nullptr;
251
252 // We found some types in dependent base classes. Recover as if the user
253 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
254 // lookup during template instantiation.
255 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256
257 ASTContext &Context = S.Context;
258 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259 cast<Type>(Context.getRecordType(RD)));
260 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261
262 CXXScopeSpec SS;
263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264
265 TypeLocBuilder Builder;
266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267 DepTL.setNameLoc(NameLoc);
268 DepTL.setElaboratedKeywordLoc(SourceLocation());
269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271}
272
273/// If the identifier refers to a type name within this scope,
274/// return the declaration of that type.
275///
276/// This routine performs ordinary name lookup of the identifier II
277/// within the given scope, with optional C++ scope specifier SS, to
278/// determine whether the name refers to a type. If so, returns an
279/// opaque pointer (actually a QualType) corresponding to that
280/// type. Otherwise, returns NULL.
281ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282 Scope *S, CXXScopeSpec *SS,
283 bool isClassName, bool HasTrailingDot,
284 ParsedType ObjectTypePtr,
285 bool IsCtorOrDtorName,
286 bool WantNontrivialTypeSourceInfo,
287 bool IsClassTemplateDeductionContext,
288 IdentifierInfo **CorrectedII) {
289 // FIXME: Consider allowing this outside C++1z mode as an extension.
290 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292 !isClassName && !HasTrailingDot;
293
294 // Determine where we will perform name lookup.
295 DeclContext *LookupCtx = nullptr;
296 if (ObjectTypePtr) {
297 QualType ObjectType = ObjectTypePtr.get();
298 if (ObjectType->isRecordType())
299 LookupCtx = computeDeclContext(ObjectType);
300 } else if (SS && SS->isNotEmpty()) {
301 LookupCtx = computeDeclContext(*SS, false);
302
303 if (!LookupCtx) {
304 if (isDependentScopeSpecifier(*SS)) {
305 // C++ [temp.res]p3:
306 // A qualified-id that refers to a type and in which the
307 // nested-name-specifier depends on a template-parameter (14.6.2)
308 // shall be prefixed by the keyword typename to indicate that the
309 // qualified-id denotes a type, forming an
310 // elaborated-type-specifier (7.1.5.3).
311 //
312 // We therefore do not perform any name lookup if the result would
313 // refer to a member of an unknown specialization.
314 if (!isClassName && !IsCtorOrDtorName)
315 return nullptr;
316
317 // We know from the grammar that this name refers to a type,
318 // so build a dependent node to describe the type.
319 if (WantNontrivialTypeSourceInfo)
320 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321
322 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324 II, NameLoc);
325 return ParsedType::make(T);
326 }
327
328 return nullptr;
329 }
330
331 if (!LookupCtx->isDependentContext() &&
332 RequireCompleteDeclContext(*SS, LookupCtx))
333 return nullptr;
334 }
335
336 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337 // lookup for class-names.
338 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339 LookupOrdinaryName;
340 LookupResult Result(*this, &II, NameLoc, Kind);
341 if (LookupCtx) {
342 // Perform "qualified" name lookup into the declaration context we
343 // computed, which is either the type of the base of a member access
344 // expression or the declaration context associated with a prior
345 // nested-name-specifier.
346 LookupQualifiedName(Result, LookupCtx);
347
348 if (ObjectTypePtr && Result.empty()) {
349 // C++ [basic.lookup.classref]p3:
350 // If the unqualified-id is ~type-name, the type-name is looked up
351 // in the context of the entire postfix-expression. If the type T of
352 // the object expression is of a class type C, the type-name is also
353 // looked up in the scope of class C. At least one of the lookups shall
354 // find a name that refers to (possibly cv-qualified) T.
355 LookupName(Result, S);
356 }
357 } else {
358 // Perform unqualified name lookup.
359 LookupName(Result, S);
360
361 // For unqualified lookup in a class template in MSVC mode, look into
362 // dependent base classes where the primary class template is known.
363 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364 if (ParsedType TypeInBase =
365 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366 return TypeInBase;
367 }
368 }
369
370 NamedDecl *IIDecl = nullptr;
371 switch (Result.getResultKind()) {
372 case LookupResult::NotFound:
373 case LookupResult::NotFoundInCurrentInstantiation:
374 if (CorrectedII) {
375 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376 AllowDeducedTemplate);
377 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378 S, SS, CCC, CTK_ErrorRecovery);
379 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380 TemplateTy Template;
381 bool MemberOfUnknownSpecialization;
382 UnqualifiedId TemplateName;
383 TemplateName.setIdentifier(NewII, NameLoc);
384 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385 CXXScopeSpec NewSS, *NewSSPtr = SS;
386 if (SS && NNS) {
387 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388 NewSSPtr = &NewSS;
389 }
390 if (Correction && (NNS || NewII != &II) &&
391 // Ignore a correction to a template type as the to-be-corrected
392 // identifier is not a template (typo correction for template names
393 // is handled elsewhere).
394 !(getLangOpts().CPlusPlus && NewSSPtr &&
395 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396 Template, MemberOfUnknownSpecialization))) {
397 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398 isClassName, HasTrailingDot, ObjectTypePtr,
399 IsCtorOrDtorName,
400 WantNontrivialTypeSourceInfo,
401 IsClassTemplateDeductionContext);
402 if (Ty) {
403 diagnoseTypo(Correction,
404 PDiag(diag::err_unknown_type_or_class_name_suggest)
405 << Result.getLookupName() << isClassName);
406 if (SS && NNS)
407 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408 *CorrectedII = NewII;
409 return Ty;
410 }
411 }
412 }
413 // If typo correction failed or was not performed, fall through
414 LLVM_FALLTHROUGH;
415 case LookupResult::FoundOverloaded:
416 case LookupResult::FoundUnresolvedValue:
417 Result.suppressDiagnostics();
418 return nullptr;
419
420 case LookupResult::Ambiguous:
421 // Recover from type-hiding ambiguities by hiding the type. We'll
422 // do the lookup again when looking for an object, and we can
423 // diagnose the error then. If we don't do this, then the error
424 // about hiding the type will be immediately followed by an error
425 // that only makes sense if the identifier was treated like a type.
426 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427 Result.suppressDiagnostics();
428 return nullptr;
429 }
430
431 // Look to see if we have a type anywhere in the list of results.
432 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433 Res != ResEnd; ++Res) {
434 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436 if (!IIDecl ||
437 (*Res)->getLocation().getRawEncoding() <
438 IIDecl->getLocation().getRawEncoding())
439 IIDecl = *Res;
440 }
441 }
442
443 if (!IIDecl) {
444 // None of the entities we found is a type, so there is no way
445 // to even assume that the result is a type. In this case, don't
446 // complain about the ambiguity. The parser will either try to
447 // perform this lookup again (e.g., as an object name), which
448 // will produce the ambiguity, or will complain that it expected
449 // a type name.
450 Result.suppressDiagnostics();
451 return nullptr;
452 }
453
454 // We found a type within the ambiguous lookup; diagnose the
455 // ambiguity and then return that type. This might be the right
456 // answer, or it might not be, but it suppresses any attempt to
457 // perform the name lookup again.
458 break;
459
460 case LookupResult::Found:
461 IIDecl = Result.getFoundDecl();
462 break;
463 }
464
465 assert(IIDecl && "Didn't find decl");
466
467 QualType T;
468 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469 // C++ [class.qual]p2: A lookup that would find the injected-class-name
470 // instead names the constructors of the class, except when naming a class.
471 // This is ill-formed when we're not actually forming a ctor or dtor name.
472 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475 FoundRD->isInjectedClassName() &&
476 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478 << &II << /*Type*/1;
479
480 DiagnoseUseOfDecl(IIDecl, NameLoc);
481
482 T = Context.getTypeDeclType(TD);
483 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486 if (!HasTrailingDot)
487 T = Context.getObjCInterfaceType(IDecl);
488 } else if (AllowDeducedTemplate) {
489 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491 QualType(), false);
492 }
493
494 if (T.isNull()) {
495 // If it's not plausibly a type, suppress diagnostics.
496 Result.suppressDiagnostics();
497 return nullptr;
498 }
499
500 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501 // constructor or destructor name (in such a case, the scope specifier
502 // will be attached to the enclosing Expr or Decl node).
503 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504 !isa<ObjCInterfaceDecl>(IIDecl)) {
505 if (WantNontrivialTypeSourceInfo) {
506 // Construct a type with type-source information.
507 TypeLocBuilder Builder;
508 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509
510 T = getElaboratedType(ETK_None, *SS, T);
511 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512 ElabTL.setElaboratedKeywordLoc(SourceLocation());
513 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515 } else {
516 T = getElaboratedType(ETK_None, *SS, T);
517 }
518 }
519
520 return ParsedType::make(T);
521}
522
523// Builds a fake NNS for the given decl context.
524static NestedNameSpecifier *
525synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526 for (;; DC = DC->getLookupParent()) {
527 DC = DC->getPrimaryContext();
528 auto *ND = dyn_cast<NamespaceDecl>(DC);
529 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530 return NestedNameSpecifier::Create(Context, nullptr, ND);
531 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533 RD->getTypeForDecl());
534 else if (isa<TranslationUnitDecl>(DC))
535 return NestedNameSpecifier::GlobalSpecifier(Context);
536 }
537 llvm_unreachable("something isn't in TU scope?");
538}
539
540/// Find the parent class with dependent bases of the innermost enclosing method
541/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542/// up allowing unqualified dependent type names at class-level, which MSVC
543/// correctly rejects.
544static const CXXRecordDecl *
545findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547 DC = DC->getPrimaryContext();
548 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549 if (MD->getParent()->hasAnyDependentBases())
550 return MD->getParent();
551 }
552 return nullptr;
553}
554
555ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556 SourceLocation NameLoc,
557 bool IsTemplateTypeArg) {
558 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559
560 NestedNameSpecifier *NNS = nullptr;
561 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562 // If we weren't able to parse a default template argument, delay lookup
563 // until instantiation time by making a non-dependent DependentTypeName. We
564 // pretend we saw a NestedNameSpecifier referring to the current scope, and
565 // lookup is retried.
566 // FIXME: This hurts our diagnostic quality, since we get errors like "no
567 // type named 'Foo' in 'current_namespace'" when the user didn't write any
568 // name specifiers.
569 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571 } else if (const CXXRecordDecl *RD =
572 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573 // Build a DependentNameType that will perform lookup into RD at
574 // instantiation time.
575 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576 RD->getTypeForDecl());
577
578 // Diagnose that this identifier was undeclared, and retry the lookup during
579 // template instantiation.
580 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581 << RD;
582 } else {
583 // This is not a situation that we should recover from.
584 return ParsedType();
585 }
586
587 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588
589 // Build type location information. We synthesized the qualifier, so we have
590 // to build a fake NestedNameSpecifierLoc.
591 NestedNameSpecifierLocBuilder NNSLocBuilder;
592 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594
595 TypeLocBuilder Builder;
596 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597 DepTL.setNameLoc(NameLoc);
598 DepTL.setElaboratedKeywordLoc(SourceLocation());
599 DepTL.setQualifierLoc(QualifierLoc);
600 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601}
602
603/// isTagName() - This method is called *for error recovery purposes only*
604/// to determine if the specified name is a valid tag name ("struct foo"). If
605/// so, this returns the TST for the tag corresponding to it (TST_enum,
606/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
607/// cases in C where the user forgot to specify the tag.
608DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609 // Do a tag name lookup in this scope.
610 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611 LookupName(R, S, false);
612 R.suppressDiagnostics();
613 if (R.getResultKind() == LookupResult::Found)
614 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615 switch (TD->getTagKind()) {
616 case TTK_Struct: return DeclSpec::TST_struct;
617 case TTK_Interface: return DeclSpec::TST_interface;
618 case TTK_Union: return DeclSpec::TST_union;
619 case TTK_Class: return DeclSpec::TST_class;
620 case TTK_Enum: return DeclSpec::TST_enum;
621 }
622 }
623
624 return DeclSpec::TST_unspecified;
625}
626
627/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628/// if a CXXScopeSpec's type is equal to the type of one of the base classes
629/// then downgrade the missing typename error to a warning.
630/// This is needed for MSVC compatibility; Example:
631/// @code
632/// template<class T> class A {
633/// public:
634/// typedef int TYPE;
635/// };
636/// template<class T> class B : public A<T> {
637/// public:
638/// A<T>::TYPE a; // no typename required because A<T> is a base class.
639/// };
640/// @endcode
641bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642 if (CurContext->isRecord()) {
643 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644 return true;
645
646 const Type *Ty = SS->getScopeRep()->getAsType();
647
648 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649 for (const auto &Base : RD->bases())
650 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651 return true;
652 return S->isFunctionPrototypeScope();
653 }
654 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655}
656
657void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658 SourceLocation IILoc,
659 Scope *S,
660 CXXScopeSpec *SS,
661 ParsedType &SuggestedType,
662 bool IsTemplateName) {
663 // Don't report typename errors for editor placeholders.
664 if (II->isEditorPlaceholder())
665 return;
666 // We don't have anything to suggest (yet).
667 SuggestedType = nullptr;
668
669 // There may have been a typo in the name of the type. Look up typo
670 // results, in case we have something that we can suggest.
671 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672 /*AllowTemplates=*/IsTemplateName,
673 /*AllowNonTemplates=*/!IsTemplateName);
674 if (TypoCorrection Corrected =
675 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676 CCC, CTK_ErrorRecovery)) {
677 // FIXME: Support error recovery for the template-name case.
678 bool CanRecover = !IsTemplateName;
679 if (Corrected.isKeyword()) {
680 // We corrected to a keyword.
681 diagnoseTypo(Corrected,
682 PDiag(IsTemplateName ? diag::err_no_template_suggest
683 : diag::err_unknown_typename_suggest)
684 << II);
685 II = Corrected.getCorrectionAsIdentifierInfo();
686 } else {
687 // We found a similarly-named type or interface; suggest that.
688 if (!SS || !SS->isSet()) {
689 diagnoseTypo(Corrected,
690 PDiag(IsTemplateName ? diag::err_no_template_suggest
691 : diag::err_unknown_typename_suggest)
692 << II, CanRecover);
693 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696 II->getName().equals(CorrectedStr);
697 diagnoseTypo(Corrected,
698 PDiag(IsTemplateName
699 ? diag::err_no_member_template_suggest
700 : diag::err_unknown_nested_typename_suggest)
701 << II << DC << DroppedSpecifier << SS->getRange(),
702 CanRecover);
703 } else {
704 llvm_unreachable("could not have corrected a typo here");
705 }
706
707 if (!CanRecover)
708 return;
709
710 CXXScopeSpec tmpSS;
711 if (Corrected.getCorrectionSpecifier())
712 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713 SourceRange(IILoc));
714 // FIXME: Support class template argument deduction here.
715 SuggestedType =
716 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718 /*IsCtorOrDtorName=*/false,
719 /*NonTrivialTypeSourceInfo=*/true);
720 }
721 return;
722 }
723
724 if (getLangOpts().CPlusPlus && !IsTemplateName) {
725 // See if II is a class template that the user forgot to pass arguments to.
726 UnqualifiedId Name;
727 Name.setIdentifier(II, IILoc);
728 CXXScopeSpec EmptySS;
729 TemplateTy TemplateResult;
730 bool MemberOfUnknownSpecialization;
731 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732 Name, nullptr, true, TemplateResult,
733 MemberOfUnknownSpecialization) == TNK_Type_template) {
734 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735 return;
736 }
737 }
738
739 // FIXME: Should we move the logic that tries to recover from a missing tag
740 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741
742 if (!SS || (!SS->isSet() && !SS->isInvalid()))
743 Diag(IILoc, IsTemplateName ? diag::err_no_template
744 : diag::err_unknown_typename)
745 << II;
746 else if (DeclContext *DC = computeDeclContext(*SS, false))
747 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748 : diag::err_typename_nested_not_found)
749 << II << DC << SS->getRange();
750 else if (isDependentScopeSpecifier(*SS)) {
751 unsigned DiagID = diag::err_typename_missing;
752 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753 DiagID = diag::ext_typename_missing;
754
755 Diag(SS->getRange().getBegin(), DiagID)
756 << SS->getScopeRep() << II->getName()
757 << SourceRange(SS->getRange().getBegin(), IILoc)
758 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759 SuggestedType = ActOnTypenameType(S, SourceLocation(),
760 *SS, *II, IILoc).get();
761 } else {
762 assert(SS && SS->isInvalid() &&
763 "Invalid scope specifier has already been diagnosed");
764 }
765}
766
767/// Determine whether the given result set contains either a type name
768/// or
769static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771 NextToken.is(tok::less);
772
773 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775 return true;
776
777 if (CheckTemplate && isa<TemplateDecl>(*I))
778 return true;
779 }
780
781 return false;
782}
783
784static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785 Scope *S, CXXScopeSpec &SS,
786 IdentifierInfo *&Name,
787 SourceLocation NameLoc) {
788 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789 SemaRef.LookupParsedName(R, S, &SS);
790 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791 StringRef FixItTagName;
792 switch (Tag->getTagKind()) {
793 case TTK_Class:
794 FixItTagName = "class ";
795 break;
796
797 case TTK_Enum:
798 FixItTagName = "enum ";
799 break;
800
801 case TTK_Struct:
802 FixItTagName = "struct ";
803 break;
804
805 case TTK_Interface:
806 FixItTagName = "__interface ";
807 break;
808
809 case TTK_Union:
810 FixItTagName = "union ";
811 break;
812 }
813
814 StringRef TagName = FixItTagName.drop_back();
815 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818
819 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820 I != IEnd; ++I)
821 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822 << Name << TagName;
823
824 // Replace lookup results with just the tag decl.
825 Result.clear(Sema::LookupTagName);
826 SemaRef.LookupParsedName(Result, S, &SS);
827 return true;
828 }
829
830 return false;
831}
832
833/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835 QualType T, SourceLocation NameLoc) {
836 ASTContext &Context = S.Context;
837
838 TypeLocBuilder Builder;
839 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840
841 T = S.getElaboratedType(ETK_None, SS, T);
842 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843 ElabTL.setElaboratedKeywordLoc(SourceLocation());
844 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846}
847
848Sema::NameClassification
849Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
850 SourceLocation NameLoc, const Token &NextToken,
851 bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
852 DeclarationNameInfo NameInfo(Name, NameLoc);
853 ObjCMethodDecl *CurMethod = getCurMethodDecl();
854
855 if (NextToken.is(tok::coloncolon)) {
856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859 isCurrentClassName(*Name, S, &SS)) {
860 // Per [class.qual]p2, this names the constructors of SS, not the
861 // injected-class-name. We don't have a classification for that.
862 // There's not much point caching this result, since the parser
863 // will reject it later.
864 return NameClassification::Unknown();
865 }
866
867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868 LookupParsedName(Result, S, &SS, !CurMethod);
869
870 // For unqualified lookup in a class template in MSVC mode, look into
871 // dependent base classes where the primary class template is known.
872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873 if (ParsedType TypeInBase =
874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875 return TypeInBase;
876 }
877
878 // Perform lookup for Objective-C instance variables (including automatically
879 // synthesized instance variables), if we're in an Objective-C method.
880 // FIXME: This lookup really, really needs to be folded in to the normal
881 // unqualified lookup mechanism.
882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884 if (E.get() || E.isInvalid())
885 return E;
886 }
887
888 bool SecondTry = false;
889 bool IsFilteredTemplateName = false;
890
891Corrected:
892 switch (Result.getResultKind()) {
893 case LookupResult::NotFound:
894 // If an unqualified-id is followed by a '(', then we have a function
895 // call.
896 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897 // In C++, this is an ADL-only call.
898 // FIXME: Reference?
899 if (getLangOpts().CPlusPlus)
900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901
902 // C90 6.3.2.2:
903 // If the expression that precedes the parenthesized argument list in a
904 // function call consists solely of an identifier, and if no
905 // declaration is visible for this identifier, the identifier is
906 // implicitly declared exactly as if, in the innermost block containing
907 // the function call, the declaration
908 //
909 // extern int identifier ();
910 //
911 // appeared.
912 //
913 // We also allow this in C99 as an extension.
914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915 Result.addDecl(D);
916 Result.resolveKind();
917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918 }
919 }
920
921 if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
922 // In C++20 onwards, this could be an ADL-only call to a function
923 // template, and we're required to assume that this is a template name.
924 //
925 // FIXME: Find a way to still do typo correction in this case.
926 TemplateName Template =
927 Context.getAssumedTemplateName(NameInfo.getName());
928 return NameClassification::UndeclaredTemplate(Template);
929 }
930
931 // In C, we first see whether there is a tag type by the same name, in
932 // which case it's likely that the user just forgot to write "enum",
933 // "struct", or "union".
934 if (!getLangOpts().CPlusPlus && !SecondTry &&
935 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
936 break;
937 }
938
939 // Perform typo correction to determine if there is another name that is
940 // close to this name.
941 if (!SecondTry && CCC) {
942 SecondTry = true;
943 if (TypoCorrection Corrected =
944 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
945 &SS, *CCC, CTK_ErrorRecovery)) {
946 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
947 unsigned QualifiedDiag = diag::err_no_member_suggest;
948
949 NamedDecl *FirstDecl = Corrected.getFoundDecl();
950 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
951 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
952 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
953 UnqualifiedDiag = diag::err_no_template_suggest;
954 QualifiedDiag = diag::err_no_member_template_suggest;
955 } else if (UnderlyingFirstDecl &&
956 (isa<TypeDecl>(UnderlyingFirstDecl) ||
957 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
958 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
959 UnqualifiedDiag = diag::err_unknown_typename_suggest;
960 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
961 }
962
963 if (SS.isEmpty()) {
964 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
965 } else {// FIXME: is this even reachable? Test it.
966 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
967 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
968 Name->getName().equals(CorrectedStr);
969 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
970 << Name << computeDeclContext(SS, false)
971 << DroppedSpecifier << SS.getRange());
972 }
973
974 // Update the name, so that the caller has the new name.
975 Name = Corrected.getCorrectionAsIdentifierInfo();
976
977 // Typo correction corrected to a keyword.
978 if (Corrected.isKeyword())
979 return Name;
980
981 // Also update the LookupResult...
982 // FIXME: This should probably go away at some point
983 Result.clear();
984 Result.setLookupName(Corrected.getCorrection());
985 if (FirstDecl)
986 Result.addDecl(FirstDecl);
987
988 // If we found an Objective-C instance variable, let
989 // LookupInObjCMethod build the appropriate expression to
990 // reference the ivar.
991 // FIXME: This is a gross hack.
992 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
993 Result.clear();
994 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
995 return E;
996 }
997
998 goto Corrected;
999 }
1000 }
1001
1002 // We failed to correct; just fall through and let the parser deal with it.
1003 Result.suppressDiagnostics();
1004 return NameClassification::Unknown();
1005
1006 case LookupResult::NotFoundInCurrentInstantiation: {
1007 // We performed name lookup into the current instantiation, and there were
1008 // dependent bases, so we treat this result the same way as any other
1009 // dependent nested-name-specifier.
1010
1011 // C++ [temp.res]p2:
1012 // A name used in a template declaration or definition and that is
1013 // dependent on a template-parameter is assumed not to name a type
1014 // unless the applicable name lookup finds a type name or the name is
1015 // qualified by the keyword typename.
1016 //
1017 // FIXME: If the next token is '<', we might want to ask the parser to
1018 // perform some heroics to see if we actually have a
1019 // template-argument-list, which would indicate a missing 'template'
1020 // keyword here.
1021 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1022 NameInfo, IsAddressOfOperand,
1023 /*TemplateArgs=*/nullptr);
1024 }
1025
1026 case LookupResult::Found:
1027 case LookupResult::FoundOverloaded:
1028 case LookupResult::FoundUnresolvedValue:
1029 break;
1030
1031 case LookupResult::Ambiguous:
1032 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1033 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1034 /*AllowDependent=*/false)) {
1035 // C++ [temp.local]p3:
1036 // A lookup that finds an injected-class-name (10.2) can result in an
1037 // ambiguity in certain cases (for example, if it is found in more than
1038 // one base class). If all of the injected-class-names that are found
1039 // refer to specializations of the same class template, and if the name
1040 // is followed by a template-argument-list, the reference refers to the
1041 // class template itself and not a specialization thereof, and is not
1042 // ambiguous.
1043 //
1044 // This filtering can make an ambiguous result into an unambiguous one,
1045 // so try again after filtering out template names.
1046 FilterAcceptableTemplateNames(Result);
1047 if (!Result.isAmbiguous()) {
1048 IsFilteredTemplateName = true;
1049 break;
1050 }
1051 }
1052
1053 // Diagnose the ambiguity and return an error.
1054 return NameClassification::Error();
1055 }
1056
1057 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058 (IsFilteredTemplateName ||
1059 hasAnyAcceptableTemplateNames(
1060 Result, /*AllowFunctionTemplates=*/true,
1061 /*AllowDependent=*/false,
1062 /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1063 getLangOpts().CPlusPlus2a))) {
1064 // C++ [temp.names]p3:
1065 // After name lookup (3.4) finds that a name is a template-name or that
1066 // an operator-function-id or a literal- operator-id refers to a set of
1067 // overloaded functions any member of which is a function template if
1068 // this is followed by a <, the < is always taken as the delimiter of a
1069 // template-argument-list and never as the less-than operator.
1070 // C++2a [temp.names]p2:
1071 // A name is also considered to refer to a template if it is an
1072 // unqualified-id followed by a < and name lookup finds either one
1073 // or more functions or finds nothing.
1074 if (!IsFilteredTemplateName)
1075 FilterAcceptableTemplateNames(Result);
1076
1077 bool IsFunctionTemplate;
1078 bool IsVarTemplate;
1079 TemplateName Template;
1080 if (Result.end() - Result.begin() > 1) {
1081 IsFunctionTemplate = true;
1082 Template = Context.getOverloadedTemplateName(Result.begin(),
1083 Result.end());
1084 } else if (!Result.empty()) {
1085 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1086 *Result.begin(), /*AllowFunctionTemplates=*/true,
1087 /*AllowDependent=*/false));
1088 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1089 IsVarTemplate = isa<VarTemplateDecl>(TD);
1090
1091 if (SS.isSet() && !SS.isInvalid())
1092 Template =
1093 Context.getQualifiedTemplateName(SS.getScopeRep(),
1094 /*TemplateKeyword=*/false, TD);
1095 else
1096 Template = TemplateName(TD);
1097 } else {
1098 // All results were non-template functions. This is a function template
1099 // name.
1100 IsFunctionTemplate = true;
1101 Template = Context.getAssumedTemplateName(NameInfo.getName());
1102 }
1103
1104 if (IsFunctionTemplate) {
1105 // Function templates always go through overload resolution, at which
1106 // point we'll perform the various checks (e.g., accessibility) we need
1107 // to based on which function we selected.
1108 Result.suppressDiagnostics();
1109
1110 return NameClassification::FunctionTemplate(Template);
1111 }
1112
1113 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1114 : NameClassification::TypeTemplate(Template);
1115 }
1116
1117 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1118 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1119 DiagnoseUseOfDecl(Type, NameLoc);
1120 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1121 QualType T = Context.getTypeDeclType(Type);
1122 if (SS.isNotEmpty())
1123 return buildNestedType(*this, SS, T, NameLoc);
1124 return ParsedType::make(T);
1125 }
1126
1127 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1128 if (!Class) {
1129 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1130 if (ObjCCompatibleAliasDecl *Alias =
1131 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1132 Class = Alias->getClassInterface();
1133 }
1134
1135 if (Class) {
1136 DiagnoseUseOfDecl(Class, NameLoc);
1137
1138 if (NextToken.is(tok::period)) {
1139 // Interface. <something> is parsed as a property reference expression.
1140 // Just return "unknown" as a fall-through for now.
1141 Result.suppressDiagnostics();
1142 return NameClassification::Unknown();
1143 }
1144
1145 QualType T = Context.getObjCInterfaceType(Class);
1146 return ParsedType::make(T);
1147 }
1148
1149 // We can have a type template here if we're classifying a template argument.
1150 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1151 !isa<VarTemplateDecl>(FirstDecl))
1152 return NameClassification::TypeTemplate(
1153 TemplateName(cast<TemplateDecl>(FirstDecl)));
1154
1155 // Check for a tag type hidden by a non-type decl in a few cases where it
1156 // seems likely a type is wanted instead of the non-type that was found.
1157 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1158 if ((NextToken.is(tok::identifier) ||
1159 (NextIsOp &&
1160 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1161 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1162 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1163 DiagnoseUseOfDecl(Type, NameLoc);
1164 QualType T = Context.getTypeDeclType(Type);
1165 if (SS.isNotEmpty())
1166 return buildNestedType(*this, SS, T, NameLoc);
1167 return ParsedType::make(T);
1168 }
1169
1170 if (FirstDecl->isCXXClassMember())
1171 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1172 nullptr, S);
1173
1174 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1175 return BuildDeclarationNameExpr(SS, Result, ADL);
1176}
1177
1178Sema::TemplateNameKindForDiagnostics
1179Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1180 auto *TD = Name.getAsTemplateDecl();
1181 if (!TD)
1182 return TemplateNameKindForDiagnostics::DependentTemplate;
1183 if (isa<ClassTemplateDecl>(TD))
1184 return TemplateNameKindForDiagnostics::ClassTemplate;
1185 if (isa<FunctionTemplateDecl>(TD))
1186 return TemplateNameKindForDiagnostics::FunctionTemplate;
1187 if (isa<VarTemplateDecl>(TD))
1188 return TemplateNameKindForDiagnostics::VarTemplate;
1189 if (isa<TypeAliasTemplateDecl>(TD))
1190 return TemplateNameKindForDiagnostics::AliasTemplate;
1191 if (isa<TemplateTemplateParmDecl>(TD))
1192 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1193 return TemplateNameKindForDiagnostics::DependentTemplate;
1194}
1195
1196// Determines the context to return to after temporarily entering a
1197// context. This depends in an unnecessarily complicated way on the
1198// exact ordering of callbacks from the parser.
1199DeclContext *Sema::getContainingDC(DeclContext *DC) {
1200
1201 // Functions defined inline within classes aren't parsed until we've
1202 // finished parsing the top-level class, so the top-level class is
1203 // the context we'll need to return to.
1204 // A Lambda call operator whose parent is a class must not be treated
1205 // as an inline member function. A Lambda can be used legally
1206 // either as an in-class member initializer or a default argument. These
1207 // are parsed once the class has been marked complete and so the containing
1208 // context would be the nested class (when the lambda is defined in one);
1209 // If the class is not complete, then the lambda is being used in an
1210 // ill-formed fashion (such as to specify the width of a bit-field, or
1211 // in an array-bound) - in which case we still want to return the
1212 // lexically containing DC (which could be a nested class).
1213 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1214 DC = DC->getLexicalParent();
1215
1216 // A function not defined within a class will always return to its
1217 // lexical context.
1218 if (!isa<CXXRecordDecl>(DC))
1219 return DC;
1220
1221 // A C++ inline method/friend is parsed *after* the topmost class
1222 // it was declared in is fully parsed ("complete"); the topmost
1223 // class is the context we need to return to.
1224 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1225 DC = RD;
1226
1227 // Return the declaration context of the topmost class the inline method is
1228 // declared in.
1229 return DC;
1230 }
1231
1232 return DC->getLexicalParent();
1233}
1234
1235void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1236 assert(getContainingDC(DC) == CurContext &&
1237 "The next DeclContext should be lexically contained in the current one.");
1238 CurContext = DC;
1239 S->setEntity(DC);
1240}
1241
1242void Sema::PopDeclContext() {
1243 assert(CurContext && "DeclContext imbalance!");
1244
1245 CurContext = getContainingDC(CurContext);
1246 assert(CurContext && "Popped translation unit!");
1247}
1248
1249Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1250 Decl *D) {
1251 // Unlike PushDeclContext, the context to which we return is not necessarily
1252 // the containing DC of TD, because the new context will be some pre-existing
1253 // TagDecl definition instead of a fresh one.
1254 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1255 CurContext = cast<TagDecl>(D)->getDefinition();
1256 assert(CurContext && "skipping definition of undefined tag");
1257 // Start lookups from the parent of the current context; we don't want to look
1258 // into the pre-existing complete definition.
1259 S->setEntity(CurContext->getLookupParent());
1260 return Result;
1261}
1262
1263void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1264 CurContext = static_cast<decltype(CurContext)>(Context);
1265}
1266
1267/// EnterDeclaratorContext - Used when we must lookup names in the context
1268/// of a declarator's nested name specifier.
1269///
1270void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1271 // C++0x [basic.lookup.unqual]p13:
1272 // A name used in the definition of a static data member of class
1273 // X (after the qualified-id of the static member) is looked up as
1274 // if the name was used in a member function of X.
1275 // C++0x [basic.lookup.unqual]p14:
1276 // If a variable member of a namespace is defined outside of the
1277 // scope of its namespace then any name used in the definition of
1278 // the variable member (after the declarator-id) is looked up as
1279 // if the definition of the variable member occurred in its
1280 // namespace.
1281 // Both of these imply that we should push a scope whose context
1282 // is the semantic context of the declaration. We can't use
1283 // PushDeclContext here because that context is not necessarily
1284 // lexically contained in the current context. Fortunately,
1285 // the containing scope should have the appropriate information.
1286
1287 assert(!S->getEntity() && "scope already has entity");
1288
1289#ifndef NDEBUG
1290 Scope *Ancestor = S->getParent();
1291 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1292 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1293#endif
1294
1295 CurContext = DC;
1296 S->setEntity(DC);
1297}
1298
1299void Sema::ExitDeclaratorContext(Scope *S) {
1300 assert(S->getEntity() == CurContext && "Context imbalance!");
1301
1302 // Switch back to the lexical context. The safety of this is
1303 // enforced by an assert in EnterDeclaratorContext.
1304 Scope *Ancestor = S->getParent();
1305 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1306 CurContext = Ancestor->getEntity();
1307
1308 // We don't need to do anything with the scope, which is going to
1309 // disappear.
1310}
1311
1312void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1313 // We assume that the caller has already called
1314 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1315 FunctionDecl *FD = D->getAsFunction();
1316 if (!FD)
1317 return;
1318
1319 // Same implementation as PushDeclContext, but enters the context
1320 // from the lexical parent, rather than the top-level class.
1321 assert(CurContext == FD->getLexicalParent() &&
1322 "The next DeclContext should be lexically contained in the current one.");
1323 CurContext = FD;
1324 S->setEntity(CurContext);
1325
1326 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1327 ParmVarDecl *Param = FD->getParamDecl(P);
1328 // If the parameter has an identifier, then add it to the scope
1329 if (Param->getIdentifier()) {
1330 S->AddDecl(Param);
1331 IdResolver.AddDecl(Param);
1332 }
1333 }
1334}
1335
1336void Sema::ActOnExitFunctionContext() {
1337 // Same implementation as PopDeclContext, but returns to the lexical parent,
1338 // rather than the top-level class.
1339 assert(CurContext && "DeclContext imbalance!");
1340 CurContext = CurContext->getLexicalParent();
1341 assert(CurContext && "Popped translation unit!");
1342}
1343
1344/// Determine whether we allow overloading of the function
1345/// PrevDecl with another declaration.
1346///
1347/// This routine determines whether overloading is possible, not
1348/// whether some new function is actually an overload. It will return
1349/// true in C++ (where we can always provide overloads) or, as an
1350/// extension, in C when the previous function is already an
1351/// overloaded function declaration or has the "overloadable"
1352/// attribute.
1353static bool AllowOverloadingOfFunction(LookupResult &Previous,
1354 ASTContext &Context,
1355 const FunctionDecl *New) {
1356 if (Context.getLangOpts().CPlusPlus)
1357 return true;
1358
1359 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1360 return true;
1361
1362 return Previous.getResultKind() == LookupResult::Found &&
1363 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1364 New->hasAttr<OverloadableAttr>());
1365}
1366
1367/// Add this decl to the scope shadowed decl chains.
1368void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1369 // Move up the scope chain until we find the nearest enclosing
1370 // non-transparent context. The declaration will be introduced into this
1371 // scope.
1372 while (S->getEntity() && S->getEntity()->isTransparentContext())
1373 S = S->getParent();
1374
1375 // Add scoped declarations into their context, so that they can be
1376 // found later. Declarations without a context won't be inserted
1377 // into any context.
1378 if (AddToContext)
1379 CurContext->addDecl(D);
1380
1381 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1382 // are function-local declarations.
1383 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1384 !D->getDeclContext()->getRedeclContext()->Equals(
1385 D->getLexicalDeclContext()->getRedeclContext()) &&
1386 !D->getLexicalDeclContext()->isFunctionOrMethod())
1387 return;
1388
1389 // Template instantiations should also not be pushed into scope.
1390 if (isa<FunctionDecl>(D) &&
1391 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1392 return;
1393
1394 // If this replaces anything in the current scope,
1395 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1396 IEnd = IdResolver.end();
1397 for (; I != IEnd; ++I) {
1398 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1399 S->RemoveDecl(*I);
1400 IdResolver.RemoveDecl(*I);
1401
1402 // Should only need to replace one decl.
1403 break;
1404 }
1405 }
1406
1407 S->AddDecl(D);
1408
1409 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1410 // Implicitly-generated labels may end up getting generated in an order that
1411 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1412 // the label at the appropriate place in the identifier chain.
1413 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1414 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1415 if (IDC == CurContext) {
1416 if (!S->isDeclScope(*I))
1417 continue;
1418 } else if (IDC->Encloses(CurContext))
1419 break;
1420 }
1421
1422 IdResolver.InsertDeclAfter(I, D);
1423 } else {
1424 IdResolver.AddDecl(D);
1425 }
1426}
1427
1428bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1429 bool AllowInlineNamespace) {
1430 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1431}
1432
1433Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1434 DeclContext *TargetDC = DC->getPrimaryContext();
1435 do {
1436 if (DeclContext *ScopeDC = S->getEntity())
1437 if (ScopeDC->getPrimaryContext() == TargetDC)
1438 return S;
1439 } while ((S = S->getParent()));
1440
1441 return nullptr;
1442}
1443
1444static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1445 DeclContext*,
1446 ASTContext&);
1447
1448/// Filters out lookup results that don't fall within the given scope
1449/// as determined by isDeclInScope.
1450void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1451 bool ConsiderLinkage,
1452 bool AllowInlineNamespace) {
1453 LookupResult::Filter F = R.makeFilter();
1454 while (F.hasNext()) {
1455 NamedDecl *D = F.next();
1456
1457 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1458 continue;
1459
1460 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1461 continue;
1462
1463 F.erase();
1464 }
1465
1466 F.done();
1467}
1468
1469/// We've determined that \p New is a redeclaration of \p Old. Check that they
1470/// have compatible owning modules.
1471bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1472 // FIXME: The Modules TS is not clear about how friend declarations are
1473 // to be treated. It's not meaningful to have different owning modules for
1474 // linkage in redeclarations of the same entity, so for now allow the
1475 // redeclaration and change the owning modules to match.
1476 if (New->getFriendObjectKind() &&
1477 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1478 New->setLocalOwningModule(Old->getOwningModule());
1479 makeMergedDefinitionVisible(New);
1480 return false;
1481 }
1482
1483 Module *NewM = New->getOwningModule();
1484 Module *OldM = Old->getOwningModule();
1485
1486 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1487 NewM = NewM->Parent;
1488 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1489 OldM = OldM->Parent;
1490
1491 if (NewM == OldM)
1492 return false;
1493
1494 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1495 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1496 if (NewIsModuleInterface || OldIsModuleInterface) {
1497 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1498 // if a declaration of D [...] appears in the purview of a module, all
1499 // other such declarations shall appear in the purview of the same module
1500 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1501 << New
1502 << NewIsModuleInterface
1503 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1504 << OldIsModuleInterface
1505 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1506 Diag(Old->getLocation(), diag::note_previous_declaration);
1507 New->setInvalidDecl();
1508 return true;
1509 }
1510
1511 return false;
1512}
1513
1514static bool isUsingDecl(NamedDecl *D) {
1515 return isa<UsingShadowDecl>(D) ||
1516 isa<UnresolvedUsingTypenameDecl>(D) ||
1517 isa<UnresolvedUsingValueDecl>(D);
1518}
1519
1520/// Removes using shadow declarations from the lookup results.
1521static void RemoveUsingDecls(LookupResult &R) {
1522 LookupResult::Filter F = R.makeFilter();
1523 while (F.hasNext())
1524 if (isUsingDecl(F.next()))
1525 F.erase();
1526
1527 F.done();
1528}
1529
1530/// Check for this common pattern:
1531/// @code
1532/// class S {
1533/// S(const S&); // DO NOT IMPLEMENT
1534/// void operator=(const S&); // DO NOT IMPLEMENT
1535/// };
1536/// @endcode
1537static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1538 // FIXME: Should check for private access too but access is set after we get
1539 // the decl here.
1540 if (D->doesThisDeclarationHaveABody())
1541 return false;
1542
1543 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1544 return CD->isCopyConstructor();
1545 return D->isCopyAssignmentOperator();
1546}
1547
1548// We need this to handle
1549//
1550// typedef struct {
1551// void *foo() { return 0; }
1552// } A;
1553//
1554// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1555// for example. If 'A', foo will have external linkage. If we have '*A',
1556// foo will have no linkage. Since we can't know until we get to the end
1557// of the typedef, this function finds out if D might have non-external linkage.
1558// Callers should verify at the end of the TU if it D has external linkage or
1559// not.
1560bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1561 const DeclContext *DC = D->getDeclContext();
1562 while (!DC->isTranslationUnit()) {
1563 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1564 if (!RD->hasNameForLinkage())
1565 return true;
1566 }
1567 DC = DC->getParent();
1568 }
1569
1570 return !D->isExternallyVisible();
1571}
1572
1573// FIXME: This needs to be refactored; some other isInMainFile users want
1574// these semantics.
1575static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1576 if (S.TUKind != TU_Complete)
1577 return false;
1578 return S.SourceMgr.isInMainFile(Loc);
1579}
1580
1581bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1582 assert(D);
1583
1584 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1585 return false;
1586
1587 // Ignore all entities declared within templates, and out-of-line definitions
1588 // of members of class templates.
1589 if (D->getDeclContext()->isDependentContext() ||
1590 D->getLexicalDeclContext()->isDependentContext())
1591 return false;
1592
1593 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1594 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1595 return false;
1596 // A non-out-of-line declaration of a member specialization was implicitly
1597 // instantiated; it's the out-of-line declaration that we're interested in.
1598 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1599 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1600 return false;
1601
1602 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1603 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1604 return false;
1605 } else {
1606 // 'static inline' functions are defined in headers; don't warn.
1607 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1608 return false;
1609 }
1610
1611 if (FD->doesThisDeclarationHaveABody() &&
1612 Context.DeclMustBeEmitted(FD))
1613 return false;
1614 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1615 // Constants and utility variables are defined in headers with internal
1616 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1617 // like "inline".)
1618 if (!isMainFileLoc(*this, VD->getLocation()))
1619 return false;
1620
1621 if (Context.DeclMustBeEmitted(VD))
1622 return false;
1623
1624 if (VD->isStaticDataMember() &&
1625 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1626 return false;
1627 if (VD->isStaticDataMember() &&
1628 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1629 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1630 return false;
1631
1632 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1633 return false;
1634 } else {
1635 return false;
1636 }
1637
1638 // Only warn for unused decls internal to the translation unit.
1639 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1640 // for inline functions defined in the main source file, for instance.
1641 return mightHaveNonExternalLinkage(D);
1642}
1643
1644void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1645 if (!D)
1646 return;
1647
1648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1649 const FunctionDecl *First = FD->getFirstDecl();
1650 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1651 return; // First should already be in the vector.
1652 }
1653
1654 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1655 const VarDecl *First = VD->getFirstDecl();
1656 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1657 return; // First should already be in the vector.
1658 }
1659
1660 if (ShouldWarnIfUnusedFileScopedDecl(D))
1661 UnusedFileScopedDecls.push_back(D);
1662}
1663
1664static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1665 if (D->isInvalidDecl())
1666 return false;
1667
1668 bool Referenced = false;
1669 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1670 // For a decomposition declaration, warn if none of the bindings are
1671 // referenced, instead of if the variable itself is referenced (which
1672 // it is, by the bindings' expressions).
1673 for (auto *BD : DD->bindings()) {
1674 if (BD->isReferenced()) {
1675 Referenced = true;
1676 break;
1677 }
1678 }
1679 } else if (!D->getDeclName()) {
1680 return false;
1681 } else if (D->isReferenced() || D->isUsed()) {
1682 Referenced = true;
1683 }
1684
1685 if (Referenced || D->hasAttr<UnusedAttr>() ||
1686 D->hasAttr<ObjCPreciseLifetimeAttr>())
1687 return false;
1688
1689 if (isa<LabelDecl>(D))
1690 return true;
1691
1692 // Except for labels, we only care about unused decls that are local to
1693 // functions.
1694 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1695 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1696 // For dependent types, the diagnostic is deferred.
1697 WithinFunction =
1698 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1699 if (!WithinFunction)
1700 return false;
1701
1702 if (isa<TypedefNameDecl>(D))
1703 return true;
1704
1705 // White-list anything that isn't a local variable.
1706 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1707 return false;
1708
1709 // Types of valid local variables should be complete, so this should succeed.
1710 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1711
1712 // White-list anything with an __attribute__((unused)) type.
1713 const auto *Ty = VD->getType().getTypePtr();
1714
1715 // Only look at the outermost level of typedef.
1716 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1717 if (TT->getDecl()->hasAttr<UnusedAttr>())
1718 return false;
1719 }
1720
1721 // If we failed to complete the type for some reason, or if the type is
1722 // dependent, don't diagnose the variable.
1723 if (Ty->isIncompleteType() || Ty->isDependentType())
1724 return false;
1725
1726 // Look at the element type to ensure that the warning behaviour is
1727 // consistent for both scalars and arrays.
1728 Ty = Ty->getBaseElementTypeUnsafe();
1729
1730 if (const TagType *TT = Ty->getAs<TagType>()) {
1731 const TagDecl *Tag = TT->getDecl();
1732 if (Tag->hasAttr<UnusedAttr>())
1733 return false;
1734
1735 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1736 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1737 return false;
1738
1739 if (const Expr *Init = VD->getInit()) {
1740 if (const ExprWithCleanups *Cleanups =
1741 dyn_cast<ExprWithCleanups>(Init))
1742 Init = Cleanups->getSubExpr();
1743 const CXXConstructExpr *Construct =
1744 dyn_cast<CXXConstructExpr>(Init);
1745 if (Construct && !Construct->isElidable()) {
1746 CXXConstructorDecl *CD = Construct->getConstructor();
1747 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1748 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1749 return false;
1750 }
1751 }
1752 }
1753 }
1754
1755 // TODO: __attribute__((unused)) templates?
1756 }
1757
1758 return true;
1759}
1760
1761static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1762 FixItHint &Hint) {
1763 if (isa<LabelDecl>(D)) {
1764 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1765 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1766 true);
1767 if (AfterColon.isInvalid())
1768 return;
1769 Hint = FixItHint::CreateRemoval(
1770 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1771 }
1772}
1773
1774void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1775 if (D->getTypeForDecl()->isDependentType())
1776 return;
1777
1778 for (auto *TmpD : D->decls()) {
1779 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1780 DiagnoseUnusedDecl(T);
1781 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1782 DiagnoseUnusedNestedTypedefs(R);
1783 }
1784}
1785
1786/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1787/// unless they are marked attr(unused).
1788void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1789 if (!ShouldDiagnoseUnusedDecl(D))
1790 return;
1791
1792 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1793 // typedefs can be referenced later on, so the diagnostics are emitted
1794 // at end-of-translation-unit.
1795 UnusedLocalTypedefNameCandidates.insert(TD);
1796 return;
1797 }
1798
1799 FixItHint Hint;
1800 GenerateFixForUnusedDecl(D, Context, Hint);
1801
1802 unsigned DiagID;
1803 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1804 DiagID = diag::warn_unused_exception_param;
1805 else if (isa<LabelDecl>(D))
1806 DiagID = diag::warn_unused_label;
1807 else
1808 DiagID = diag::warn_unused_variable;
1809
1810 Diag(D->getLocation(), DiagID) << D << Hint;
1811}
1812
1813static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1814 // Verify that we have no forward references left. If so, there was a goto
1815 // or address of a label taken, but no definition of it. Label fwd
1816 // definitions are indicated with a null substmt which is also not a resolved
1817 // MS inline assembly label name.
1818 bool Diagnose = false;
1819 if (L->isMSAsmLabel())
1820 Diagnose = !L->isResolvedMSAsmLabel();
1821 else
1822 Diagnose = L->getStmt() == nullptr;
1823 if (Diagnose)
1824 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1825}
1826
1827void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1828 S->mergeNRVOIntoParent();
1829
1830 if (S->decl_empty()) return;
1831 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1832 "Scope shouldn't contain decls!");
1833
1834 for (auto *TmpD : S->decls()) {
1835 assert(TmpD && "This decl didn't get pushed??");
1836
1837 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1838 NamedDecl *D = cast<NamedDecl>(TmpD);
1839
1840 // Diagnose unused variables in this scope.
1841 if (!S->hasUnrecoverableErrorOccurred()) {
1842 DiagnoseUnusedDecl(D);
1843 if (const auto *RD = dyn_cast<RecordDecl>(D))
1844 DiagnoseUnusedNestedTypedefs(RD);
1845 }
1846
1847 if (!D->getDeclName()) continue;
1848
1849 // If this was a forward reference to a label, verify it was defined.
1850 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1851 CheckPoppedLabel(LD, *this);
1852
1853 // Remove this name from our lexical scope, and warn on it if we haven't
1854 // already.
1855 IdResolver.RemoveDecl(D);
1856 auto ShadowI = ShadowingDecls.find(D);
1857 if (ShadowI != ShadowingDecls.end()) {
1858 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1859 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1860 << D << FD << FD->getParent();
1861 Diag(FD->getLocation(), diag::note_previous_declaration);
1862 }
1863 ShadowingDecls.erase(ShadowI);
1864 }
1865 }
1866}
1867
1868/// Look for an Objective-C class in the translation unit.
1869///
1870/// \param Id The name of the Objective-C class we're looking for. If
1871/// typo-correction fixes this name, the Id will be updated
1872/// to the fixed name.
1873///
1874/// \param IdLoc The location of the name in the translation unit.
1875///
1876/// \param DoTypoCorrection If true, this routine will attempt typo correction
1877/// if there is no class with the given name.
1878///
1879/// \returns The declaration of the named Objective-C class, or NULL if the
1880/// class could not be found.
1881ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1882 SourceLocation IdLoc,
1883 bool DoTypoCorrection) {
1884 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1885 // creation from this context.
1886 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1887
1888 if (!IDecl && DoTypoCorrection) {
1889 // Perform typo correction at the given location, but only if we
1890 // find an Objective-C class name.
1891 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1892 if (TypoCorrection C =
1893 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1894 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1895 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1896 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1897 Id = IDecl->getIdentifier();
1898 }
1899 }
1900 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1901 // This routine must always return a class definition, if any.
1902 if (Def && Def->getDefinition())
1903 Def = Def->getDefinition();
1904 return Def;
1905}
1906
1907/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1908/// from S, where a non-field would be declared. This routine copes
1909/// with the difference between C and C++ scoping rules in structs and
1910/// unions. For example, the following code is well-formed in C but
1911/// ill-formed in C++:
1912/// @code
1913/// struct S6 {
1914/// enum { BAR } e;
1915/// };
1916///
1917/// void test_S6() {
1918/// struct S6 a;
1919/// a.e = BAR;
1920/// }
1921/// @endcode
1922/// For the declaration of BAR, this routine will return a different
1923/// scope. The scope S will be the scope of the unnamed enumeration
1924/// within S6. In C++, this routine will return the scope associated
1925/// with S6, because the enumeration's scope is a transparent
1926/// context but structures can contain non-field names. In C, this
1927/// routine will return the translation unit scope, since the
1928/// enumeration's scope is a transparent context and structures cannot
1929/// contain non-field names.
1930Scope *Sema::getNonFieldDeclScope(Scope *S) {
1931 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1932 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1933 (S->isClassScope() && !getLangOpts().CPlusPlus))
1934 S = S->getParent();
1935 return S;
1936}
1937
1938/// Looks up the declaration of "struct objc_super" and
1939/// saves it for later use in building builtin declaration of
1940/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1941/// pre-existing declaration exists no action takes place.
1942static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1943 IdentifierInfo *II) {
1944 if (!II->isStr("objc_msgSendSuper"))
1945 return;
1946 ASTContext &Context = ThisSema.Context;
1947
1948 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1949 SourceLocation(), Sema::LookupTagName);
1950 ThisSema.LookupName(Result, S);
1951 if (Result.getResultKind() == LookupResult::Found)
1952 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1953 Context.setObjCSuperType(Context.getTagDeclType(TD));
1954}
1955
1956static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1957 ASTContext::GetBuiltinTypeError Error) {
1958 switch (Error) {
1959 case ASTContext::GE_None:
1960 return "";
1961 case ASTContext::GE_Missing_type:
1962 return BuiltinInfo.getHeaderName(ID);
1963 case ASTContext::GE_Missing_stdio:
1964 return "stdio.h";
1965 case ASTContext::GE_Missing_setjmp:
1966 return "setjmp.h";
1967 case ASTContext::GE_Missing_ucontext:
1968 return "ucontext.h";
1969 case ASTContext::GE_Missing_pthread:
1970 return "pthread.h";
1971 }
1972 llvm_unreachable("unhandled error kind");
1973}
1974
1975/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1976/// file scope. lazily create a decl for it. ForRedeclaration is true
1977/// if we're creating this built-in in anticipation of redeclaring the
1978/// built-in.
1979NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1980 Scope *S, bool ForRedeclaration,
1981 SourceLocation Loc) {
1982 LookupPredefedObjCSuperType(*this, S, II);
1983
1984 ASTContext::GetBuiltinTypeError Error;
1985 QualType R = Context.GetBuiltinType(ID, Error);
1986 if (Error) {
1987 if (ForRedeclaration)
1988 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1989 << getHeaderName(Context.BuiltinInfo, ID, Error)
1990 << Context.BuiltinInfo.getName(ID);
1991 return nullptr;
1992 }
1993
1994 if (!ForRedeclaration &&
1995 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1996 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1997 Diag(Loc, diag::ext_implicit_lib_function_decl)
1998 << Context.BuiltinInfo.getName(ID) << R;
1999 if (Context.BuiltinInfo.getHeaderName(ID) &&
2000 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2001 Diag(Loc, diag::note_include_header_or_declare)
2002 << Context.BuiltinInfo.getHeaderName(ID)
2003 << Context.BuiltinInfo.getName(ID);
2004 }
2005
2006 if (R.isNull())
2007 return nullptr;
2008
2009 DeclContext *Parent = Context.getTranslationUnitDecl();
2010 if (getLangOpts().CPlusPlus) {
2011 LinkageSpecDecl *CLinkageDecl =
2012 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2013 LinkageSpecDecl::lang_c, false);
2014 CLinkageDecl->setImplicit();
2015 Parent->addDecl(CLinkageDecl);
2016 Parent = CLinkageDecl;
2017 }
2018
2019 FunctionDecl *New = FunctionDecl::Create(Context,
2020 Parent,
2021 Loc, Loc, II, R, /*TInfo=*/nullptr,
2022 SC_Extern,
2023 false,
2024 R->isFunctionProtoType());
2025 New->setImplicit();
2026
2027 // Create Decl objects for each parameter, adding them to the
2028 // FunctionDecl.
2029 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2030 SmallVector<ParmVarDecl*, 16> Params;
2031 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2032 ParmVarDecl *parm =
2033 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2034 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2035 SC_None, nullptr);
2036 parm->setScopeInfo(0, i);
2037 Params.push_back(parm);
2038 }
2039 New->setParams(Params);
2040 }
2041
2042 AddKnownFunctionAttributes(New);
2043 RegisterLocallyScopedExternCDecl(New, S);
2044
2045 // TUScope is the translation-unit scope to insert this function into.
2046 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2047 // relate Scopes to DeclContexts, and probably eliminate CurContext
2048 // entirely, but we're not there yet.
2049 DeclContext *SavedContext = CurContext;
2050 CurContext = Parent;
2051 PushOnScopeChains(New, TUScope);
2052 CurContext = SavedContext;
2053 return New;
2054}
2055
2056/// Typedef declarations don't have linkage, but they still denote the same
2057/// entity if their types are the same.
2058/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2059/// isSameEntity.
2060static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2061 TypedefNameDecl *Decl,
2062 LookupResult &Previous) {
2063 // This is only interesting when modules are enabled.
2064 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2065 return;
2066
2067 // Empty sets are uninteresting.
2068 if (Previous.empty())
2069 return;
2070
2071 LookupResult::Filter Filter = Previous.makeFilter();
2072 while (Filter.hasNext()) {
2073 NamedDecl *Old = Filter.next();
2074
2075 // Non-hidden declarations are never ignored.
2076 if (S.isVisible(Old))
2077 continue;
2078
2079 // Declarations of the same entity are not ignored, even if they have
2080 // different linkages.
2081 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2082 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2083 Decl->getUnderlyingType()))
2084 continue;
2085
2086 // If both declarations give a tag declaration a typedef name for linkage
2087 // purposes, then they declare the same entity.
2088 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2089 Decl->getAnonDeclWithTypedefName())
2090 continue;
2091 }
2092
2093 Filter.erase();
2094 }
2095
2096 Filter.done();
2097}
2098
2099bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2100 QualType OldType;
2101 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2102 OldType = OldTypedef->getUnderlyingType();
2103 else
2104 OldType = Context.getTypeDeclType(Old);
2105 QualType NewType = New->getUnderlyingType();
2106
2107 if (NewType->isVariablyModifiedType()) {
2108 // Must not redefine a typedef with a variably-modified type.
2109 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2110 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2111 << Kind << NewType;
2112 if (Old->getLocation().isValid())
2113 notePreviousDefinition(Old, New->getLocation());
2114 New->setInvalidDecl();
2115 return true;
2116 }
2117
2118 if (OldType != NewType &&
2119 !OldType->isDependentType() &&
2120 !NewType->isDependentType() &&
2121 !Context.hasSameType(OldType, NewType)) {
2122 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2123 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2124 << Kind << NewType << OldType;
2125 if (Old->getLocation().isValid())
2126 notePreviousDefinition(Old, New->getLocation());
2127 New->setInvalidDecl();
2128 return true;
2129 }
2130 return false;
2131}
2132
2133/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2134/// same name and scope as a previous declaration 'Old'. Figure out
2135/// how to resolve this situation, merging decls or emitting
2136/// diagnostics as appropriate. If there was an error, set New to be invalid.
2137///
2138void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2139 LookupResult &OldDecls) {
2140 // If the new decl is known invalid already, don't bother doing any
2141 // merging checks.
2142 if (New->isInvalidDecl()) return;
2143
2144 // Allow multiple definitions for ObjC built-in typedefs.
2145 // FIXME: Verify the underlying types are equivalent!
2146 if (getLangOpts().ObjC) {
2147 const IdentifierInfo *TypeID = New->getIdentifier();
2148 switch (TypeID->getLength()) {
2149 default: break;
2150 case 2:
2151 {
2152 if (!TypeID->isStr("id"))
2153 break;
2154 QualType T = New->getUnderlyingType();
2155 if (!T->isPointerType())
2156 break;
2157 if (!T->isVoidPointerType()) {
2158 QualType PT = T->getAs<PointerType>()->getPointeeType();
2159 if (!PT->isStructureType())
2160 break;
2161 }
2162 Context.setObjCIdRedefinitionType(T);
2163 // Install the built-in type for 'id', ignoring the current definition.
2164 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2165 return;
2166 }
2167 case 5:
2168 if (!TypeID->isStr("Class"))
2169 break;
2170 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2171 // Install the built-in type for 'Class', ignoring the current definition.
2172 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2173 return;
2174 case 3:
2175 if (!TypeID->isStr("SEL"))
2176 break;
2177 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2178 // Install the built-in type for 'SEL', ignoring the current definition.
2179 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2180 return;
2181 }
2182 // Fall through - the typedef name was not a builtin type.
2183 }
2184
2185 // Verify the old decl was also a type.
2186 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2187 if (!Old) {
2188 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2189 << New->getDeclName();
2190
2191 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2192 if (OldD->getLocation().isValid())
2193 notePreviousDefinition(OldD, New->getLocation());
2194
2195 return New->setInvalidDecl();
2196 }
2197
2198 // If the old declaration is invalid, just give up here.
2199 if (Old->isInvalidDecl())
2200 return New->setInvalidDecl();
2201
2202 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2203 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2204 auto *NewTag = New->getAnonDeclWithTypedefName();
2205 NamedDecl *Hidden = nullptr;
2206 if (OldTag && NewTag &&
2207 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2208 !hasVisibleDefinition(OldTag, &Hidden)) {
2209 // There is a definition of this tag, but it is not visible. Use it
2210 // instead of our tag.
2211 New->setTypeForDecl(OldTD->getTypeForDecl());
2212 if (OldTD->isModed())
2213 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2214 OldTD->getUnderlyingType());
2215 else
2216 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2217
2218 // Make the old tag definition visible.
2219 makeMergedDefinitionVisible(Hidden);
2220
2221 // If this was an unscoped enumeration, yank all of its enumerators
2222 // out of the scope.
2223 if (isa<EnumDecl>(NewTag)) {
2224 Scope *EnumScope = getNonFieldDeclScope(S);
2225 for (auto *D : NewTag->decls()) {
2226 auto *ED = cast<EnumConstantDecl>(D);
2227 assert(EnumScope->isDeclScope(ED));
2228 EnumScope->RemoveDecl(ED);
2229 IdResolver.RemoveDecl(ED);
2230 ED->getLexicalDeclContext()->removeDecl(ED);
2231 }
2232 }
2233 }
2234 }
2235
2236 // If the typedef types are not identical, reject them in all languages and
2237 // with any extensions enabled.
2238 if (isIncompatibleTypedef(Old, New))
2239 return;
2240
2241 // The types match. Link up the redeclaration chain and merge attributes if
2242 // the old declaration was a typedef.
2243 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2244 New->setPreviousDecl(Typedef);
2245 mergeDeclAttributes(New, Old);
2246 }
2247
2248 if (getLangOpts().MicrosoftExt)
2249 return;
2250
2251 if (getLangOpts().CPlusPlus) {
2252 // C++ [dcl.typedef]p2:
2253 // In a given non-class scope, a typedef specifier can be used to
2254 // redefine the name of any type declared in that scope to refer
2255 // to the type to which it already refers.
2256 if (!isa<CXXRecordDecl>(CurContext))
2257 return;
2258
2259 // C++0x [dcl.typedef]p4:
2260 // In a given class scope, a typedef specifier can be used to redefine
2261 // any class-name declared in that scope that is not also a typedef-name
2262 // to refer to the type to which it already refers.
2263 //
2264 // This wording came in via DR424, which was a correction to the
2265 // wording in DR56, which accidentally banned code like:
2266 //
2267 // struct S {
2268 // typedef struct A { } A;
2269 // };
2270 //
2271 // in the C++03 standard. We implement the C++0x semantics, which
2272 // allow the above but disallow
2273 //
2274 // struct S {
2275 // typedef int I;
2276 // typedef int I;
2277 // };
2278 //
2279 // since that was the intent of DR56.
2280 if (!isa<TypedefNameDecl>(Old))
2281 return;
2282
2283 Diag(New->getLocation(), diag::err_redefinition)
2284 << New->getDeclName();
2285 notePreviousDefinition(Old, New->getLocation());
2286 return New->setInvalidDecl();
2287 }
2288
2289 // Modules always permit redefinition of typedefs, as does C11.
2290 if (getLangOpts().Modules || getLangOpts().C11)
2291 return;
2292
2293 // If we have a redefinition of a typedef in C, emit a warning. This warning
2294 // is normally mapped to an error, but can be controlled with
2295 // -Wtypedef-redefinition. If either the original or the redefinition is
2296 // in a system header, don't emit this for compatibility with GCC.
2297 if (getDiagnostics().getSuppressSystemWarnings() &&
2298 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2299 (Old->isImplicit() ||
2300 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2301 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2302 return;
2303
2304 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2305 << New->getDeclName();
2306 notePreviousDefinition(Old, New->getLocation());
2307}
2308
2309/// DeclhasAttr - returns true if decl Declaration already has the target
2310/// attribute.
2311static bool DeclHasAttr(const Decl *D, const Attr *A) {
2312 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2313 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2314 for (const auto *i : D->attrs())
2315 if (i->getKind() == A->getKind()) {
2316 if (Ann) {
2317 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2318 return true;
2319 continue;
2320 }
2321 // FIXME: Don't hardcode this check
2322 if (OA && isa<OwnershipAttr>(i))
2323 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2324 return true;
2325 }
2326
2327 return false;
2328}
2329
2330static bool isAttributeTargetADefinition(Decl *D) {
2331 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2332 return VD->isThisDeclarationADefinition();
2333 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2334 return TD->isCompleteDefinition() || TD->isBeingDefined();
2335 return true;
2336}
2337
2338/// Merge alignment attributes from \p Old to \p New, taking into account the
2339/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2340///
2341/// \return \c true if any attributes were added to \p New.
2342static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2343 // Look for alignas attributes on Old, and pick out whichever attribute
2344 // specifies the strictest alignment requirement.
2345 AlignedAttr *OldAlignasAttr = nullptr;
2346 AlignedAttr *OldStrictestAlignAttr = nullptr;
2347 unsigned OldAlign = 0;
2348 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2349 // FIXME: We have no way of representing inherited dependent alignments
2350 // in a case like:
2351 // template<int A, int B> struct alignas(A) X;
2352 // template<int A, int B> struct alignas(B) X {};
2353 // For now, we just ignore any alignas attributes which are not on the
2354 // definition in such a case.
2355 if (I->isAlignmentDependent())
2356 return false;
2357
2358 if (I->isAlignas())
2359 OldAlignasAttr = I;
2360
2361 unsigned Align = I->getAlignment(S.Context);
2362 if (Align > OldAlign) {
2363 OldAlign = Align;
2364 OldStrictestAlignAttr = I;
2365 }
2366 }
2367
2368 // Look for alignas attributes on New.
2369 AlignedAttr *NewAlignasAttr = nullptr;
2370 unsigned NewAlign = 0;
2371 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2372 if (I->isAlignmentDependent())
2373 return false;
2374
2375 if (I->isAlignas())
2376 NewAlignasAttr = I;
2377
2378 unsigned Align = I->getAlignment(S.Context);
2379 if (Align > NewAlign)
2380 NewAlign = Align;
2381 }
2382
2383 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2384 // Both declarations have 'alignas' attributes. We require them to match.
2385 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2386 // fall short. (If two declarations both have alignas, they must both match
2387 // every definition, and so must match each other if there is a definition.)
2388
2389 // If either declaration only contains 'alignas(0)' specifiers, then it
2390 // specifies the natural alignment for the type.
2391 if (OldAlign == 0 || NewAlign == 0) {
2392 QualType Ty;
2393 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2394 Ty = VD->getType();
2395 else
2396 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2397
2398 if (OldAlign == 0)
2399 OldAlign = S.Context.getTypeAlign(Ty);
2400 if (NewAlign == 0)
2401 NewAlign = S.Context.getTypeAlign(Ty);
2402 }
2403
2404 if (OldAlign != NewAlign) {
2405 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2406 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2407 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2408 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2409 }
2410 }
2411
2412 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2413 // C++11 [dcl.align]p6:
2414 // if any declaration of an entity has an alignment-specifier,
2415 // every defining declaration of that entity shall specify an
2416 // equivalent alignment.
2417 // C11 6.7.5/7:
2418 // If the definition of an object does not have an alignment
2419 // specifier, any other declaration of that object shall also
2420 // have no alignment specifier.
2421 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2422 << OldAlignasAttr;
2423 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2424 << OldAlignasAttr;
2425 }
2426
2427 bool AnyAdded = false;
2428
2429 // Ensure we have an attribute representing the strictest alignment.
2430 if (OldAlign > NewAlign) {
2431 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2432 Clone->setInherited(true);
2433 New->addAttr(Clone);
2434 AnyAdded = true;
2435 }
2436
2437 // Ensure we have an alignas attribute if the old declaration had one.
2438 if (OldAlignasAttr && !NewAlignasAttr &&
2439 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2440 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2441 Clone->setInherited(true);
2442 New->addAttr(Clone);
2443 AnyAdded = true;
2444 }
2445
2446 return AnyAdded;
2447}
2448
2449static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2450 const InheritableAttr *Attr,
2451 Sema::AvailabilityMergeKind AMK) {
2452 // This function copies an attribute Attr from a previous declaration to the
2453 // new declaration D if the new declaration doesn't itself have that attribute
2454 // yet or if that attribute allows duplicates.
2455 // If you're adding a new attribute that requires logic different from
2456 // "use explicit attribute on decl if present, else use attribute from
2457 // previous decl", for example if the attribute needs to be consistent
2458 // between redeclarations, you need to call a custom merge function here.
2459 InheritableAttr *NewAttr = nullptr;
2460 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2461 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2462 NewAttr = S.mergeAvailabilityAttr(
2463 D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2464 AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2465 AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2466 AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2467 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2468 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2469 AttrSpellingListIndex);
2470 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2471 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2472 AttrSpellingListIndex);
2473 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2474 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2475 AttrSpellingListIndex);
2476 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2477 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2478 AttrSpellingListIndex);
2479 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2480 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2481 FA->getFormatIdx(), FA->getFirstArg(),
2482 AttrSpellingListIndex);
2483 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2484 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2485 AttrSpellingListIndex);
2486 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2487 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2488 AttrSpellingListIndex);
2489 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2490 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2491 AttrSpellingListIndex,
2492 IA->getSemanticSpelling());
2493 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2494 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2495 &S.Context.Idents.get(AA->getSpelling()),
2496 AttrSpellingListIndex);
2497 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2498 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2499 isa<CUDAGlobalAttr>(Attr))) {
2500 // CUDA target attributes are part of function signature for
2501 // overloading purposes and must not be merged.
2502 return false;
2503 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2504 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2505 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2506 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2507 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2508 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2509 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2510 NewAttr = S.mergeCommonAttr(D, *CommonA);
2511 else if (isa<AlignedAttr>(Attr))
2512 // AlignedAttrs are handled separately, because we need to handle all
2513 // such attributes on a declaration at the same time.
2514 NewAttr = nullptr;
2515 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2516 (AMK == Sema::AMK_Override ||
2517 AMK == Sema::AMK_ProtocolImplementation))
2518 NewAttr = nullptr;
2519 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2520 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2521 UA->getGuid());
2522 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2523 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2524 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2525 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2526 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2527 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2528
2529 if (NewAttr) {
2530 NewAttr->setInherited(true);
2531 D->addAttr(NewAttr);
2532 if (isa<MSInheritanceAttr>(NewAttr))
2533 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2534 return true;
2535 }
2536
2537 return false;
2538}
2539
2540static const NamedDecl *getDefinition(const Decl *D) {
2541 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2542 return TD->getDefinition();
2543 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2544 const VarDecl *Def = VD->getDefinition();
2545 if (Def)
2546 return Def;
2547 return VD->getActingDefinition();
2548 }
2549 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2550 return FD->getDefinition();
2551 return nullptr;
2552}
2553
2554static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2555 for (const auto *Attribute : D->attrs())
2556 if (Attribute->getKind() == Kind)
2557 return true;
2558 return false;
2559}
2560
2561/// checkNewAttributesAfterDef - If we already have a definition, check that
2562/// there are no new attributes in this declaration.
2563static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2564 if (!New->hasAttrs())
2565 return;
2566
2567 const NamedDecl *Def = getDefinition(Old);
2568 if (!Def || Def == New)
2569 return;
2570
2571 AttrVec &NewAttributes = New->getAttrs();
2572 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2573 const Attr *NewAttribute = NewAttributes[I];
2574
2575 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2576 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2577 Sema::SkipBodyInfo SkipBody;
2578 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2579
2580 // If we're skipping this definition, drop the "alias" attribute.
2581 if (SkipBody.ShouldSkip) {
2582 NewAttributes.erase(NewAttributes.begin() + I);
2583 --E;
2584 continue;
2585 }
2586 } else {
2587 VarDecl *VD = cast<VarDecl>(New);
2588 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2589 VarDecl::TentativeDefinition
2590 ? diag::err_alias_after_tentative
2591 : diag::err_redefinition;
2592 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2593 if (Diag == diag::err_redefinition)
2594 S.notePreviousDefinition(Def, VD->getLocation());
2595 else
2596 S.Diag(Def->getLocation(), diag::note_previous_definition);
2597 VD->setInvalidDecl();
2598 }
2599 ++I;
2600 continue;
2601 }
2602
2603 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2604 // Tentative definitions are only interesting for the alias check above.
2605 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2606 ++I;
2607 continue;
2608 }
2609 }
2610
2611 if (hasAttribute(Def, NewAttribute->getKind())) {
2612 ++I;
2613 continue; // regular attr merging will take care of validating this.
2614 }
2615
2616 if (isa<C11NoReturnAttr>(NewAttribute)) {
2617 // C's _Noreturn is allowed to be added to a function after it is defined.
2618 ++I;
2619 continue;
2620 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2621 if (AA->isAlignas()) {
2622 // C++11 [dcl.align]p6:
2623 // if any declaration of an entity has an alignment-specifier,
2624 // every defining declaration of that entity shall specify an
2625 // equivalent alignment.
2626 // C11 6.7.5/7:
2627 // If the definition of an object does not have an alignment
2628 // specifier, any other declaration of that object shall also
2629 // have no alignment specifier.
2630 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2631 << AA;
2632 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2633 << AA;
2634 NewAttributes.erase(NewAttributes.begin() + I);
2635 --E;
2636 continue;
2637 }
2638 }
2639
2640 S.Diag(NewAttribute->getLocation(),
2641 diag::warn_attribute_precede_definition);
2642 S.Diag(Def->getLocation(), diag::note_previous_definition);
2643 NewAttributes.erase(NewAttributes.begin() + I);
2644 --E;
2645 }
2646}
2647
2648/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2649void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2650 AvailabilityMergeKind AMK) {
2651 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2652 UsedAttr *NewAttr = OldAttr->clone(Context);
2653 NewAttr->setInherited(true);
2654 New->addAttr(NewAttr);
2655 }
2656
2657 if (!Old->hasAttrs() && !New->hasAttrs())
2658 return;
2659
2660 // Attributes declared post-definition are currently ignored.
2661 checkNewAttributesAfterDef(*this, New, Old);
2662
2663 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2664 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2665 if (OldA->getLabel() != NewA->getLabel()) {
2666 // This redeclaration changes __asm__ label.
2667 Diag(New->getLocation(), diag::err_different_asm_label);
2668 Diag(OldA->getLocation(), diag::note_previous_declaration);
2669 }
2670 } else if (Old->isUsed()) {
2671 // This redeclaration adds an __asm__ label to a declaration that has
2672 // already been ODR-used.
2673 Diag(New->getLocation(), diag::err_late_asm_label_name)
2674 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2675 }
2676 }
2677
2678 // Re-declaration cannot add abi_tag's.
2679 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2680 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2681 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2682 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2683 NewTag) == OldAbiTagAttr->tags_end()) {
2684 Diag(NewAbiTagAttr->getLocation(),
2685 diag::err_new_abi_tag_on_redeclaration)
2686 << NewTag;
2687 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2688 }
2689 }
2690 } else {
2691 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2692 Diag(Old->getLocation(), diag::note_previous_declaration);
2693 }
2694 }
2695
2696 // This redeclaration adds a section attribute.
2697 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2698 if (auto *VD = dyn_cast<VarDecl>(New)) {
2699 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2700 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2701 Diag(Old->getLocation(), diag::note_previous_declaration);
2702 }
2703 }
2704 }
2705
2706 // Redeclaration adds code-seg attribute.
2707 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2708 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2709 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2710 Diag(New->getLocation(), diag::warn_mismatched_section)
2711 << 0 /*codeseg*/;
2712 Diag(Old->getLocation(), diag::note_previous_declaration);
2713 }
2714
2715 if (!Old->hasAttrs())
2716 return;
2717
2718 bool foundAny = New->hasAttrs();
2719
2720 // Ensure that any moving of objects within the allocated map is done before
2721 // we process them.
2722 if (!foundAny) New->setAttrs(AttrVec());
2723
2724 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2725 // Ignore deprecated/unavailable/availability attributes if requested.
2726 AvailabilityMergeKind LocalAMK = AMK_None;
2727 if (isa<DeprecatedAttr>(I) ||
2728 isa<UnavailableAttr>(I) ||
2729 isa<AvailabilityAttr>(I)) {
2730 switch (AMK) {
2731 case AMK_None:
2732 continue;
2733
2734 case AMK_Redeclaration:
2735 case AMK_Override:
2736 case AMK_ProtocolImplementation:
2737 LocalAMK = AMK;
2738 break;
2739 }
2740 }
2741
2742 // Already handled.
2743 if (isa<UsedAttr>(I))
2744 continue;
2745
2746 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2747 foundAny = true;
2748 }
2749
2750 if (mergeAlignedAttrs(*this, New, Old))
2751 foundAny = true;
2752
2753 if (!foundAny) New->dropAttrs();
2754}
2755
2756/// mergeParamDeclAttributes - Copy attributes from the old parameter
2757/// to the new one.
2758static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2759 const ParmVarDecl *oldDecl,
2760 Sema &S) {
2761 // C++11 [dcl.attr.depend]p2:
2762 // The first declaration of a function shall specify the
2763 // carries_dependency attribute for its declarator-id if any declaration
2764 // of the function specifies the carries_dependency attribute.
2765 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2766 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2767 S.Diag(CDA->getLocation(),
2768 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2769 // Find the first declaration of the parameter.
2770 // FIXME: Should we build redeclaration chains for function parameters?
2771 const FunctionDecl *FirstFD =
2772 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2773 const ParmVarDecl *FirstVD =
2774 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2775 S.Diag(FirstVD->getLocation(),
2776 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2777 }
2778
2779 if (!oldDecl->hasAttrs())
2780 return;
2781
2782 bool foundAny = newDecl->hasAttrs();
2783
2784 // Ensure that any moving of objects within the allocated map is
2785 // done before we process them.
2786 if (!foundAny) newDecl->setAttrs(AttrVec());
2787
2788 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2789 if (!DeclHasAttr(newDecl, I)) {
2790 InheritableAttr *newAttr =
2791 cast<InheritableParamAttr>(I->clone(S.Context));
2792 newAttr->setInherited(true);
2793 newDecl->addAttr(newAttr);
2794 foundAny = true;
2795 }
2796 }
2797
2798 if (!foundAny) newDecl->dropAttrs();
2799}
2800
2801static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2802 const ParmVarDecl *OldParam,
2803 Sema &S) {
2804 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2805 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2806 if (*Oldnullability != *Newnullability) {
2807 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2808 << DiagNullabilityKind(
2809 *Newnullability,
2810 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2811 != 0))
2812 << DiagNullabilityKind(
2813 *Oldnullability,
2814 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2815 != 0));
2816 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2817 }
2818 } else {
2819 QualType NewT = NewParam->getType();
2820 NewT = S.Context.getAttributedType(
2821 AttributedType::getNullabilityAttrKind(*Oldnullability),
2822 NewT, NewT);
2823 NewParam->setType(NewT);
2824 }
2825 }
2826}
2827
2828namespace {
2829
2830/// Used in MergeFunctionDecl to keep track of function parameters in
2831/// C.
2832struct GNUCompatibleParamWarning {
2833 ParmVarDecl *OldParm;
2834 ParmVarDecl *NewParm;
2835 QualType PromotedType;
2836};
2837
2838} // end anonymous namespace
2839
2840/// getSpecialMember - get the special member enum for a method.
2841Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2842 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2843 if (Ctor->isDefaultConstructor())
2844 return Sema::CXXDefaultConstructor;
2845
2846 if (Ctor->isCopyConstructor())
2847 return Sema::CXXCopyConstructor;
2848
2849 if (Ctor->isMoveConstructor())
2850 return Sema::CXXMoveConstructor;
2851 } else if (isa<CXXDestructorDecl>(MD)) {
2852 return Sema::CXXDestructor;
2853 } else if (MD->isCopyAssignmentOperator()) {
2854 return Sema::CXXCopyAssignment;
2855 } else if (MD->isMoveAssignmentOperator()) {
2856 return Sema::CXXMoveAssignment;
2857 }
2858
2859 return Sema::CXXInvalid;
2860}
2861
2862// Determine whether the previous declaration was a definition, implicit
2863// declaration, or a declaration.
2864template <typename T>
2865static std::pair<diag::kind, SourceLocation>
2866getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2867 diag::kind PrevDiag;
2868 SourceLocation OldLocation = Old->getLocation();
2869 if (Old->isThisDeclarationADefinition())
2870 PrevDiag = diag::note_previous_definition;
2871 else if (Old->isImplicit()) {
2872 PrevDiag = diag::note_previous_implicit_declaration;
2873 if (OldLocation.isInvalid())
2874 OldLocation = New->getLocation();
2875 } else
2876 PrevDiag = diag::note_previous_declaration;
2877 return std::make_pair(PrevDiag, OldLocation);
2878}
2879
2880/// canRedefineFunction - checks if a function can be redefined. Currently,
2881/// only extern inline functions can be redefined, and even then only in
2882/// GNU89 mode.
2883static bool canRedefineFunction(const FunctionDecl *FD,
2884 const LangOptions& LangOpts) {
2885 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2886 !LangOpts.CPlusPlus &&
2887 FD->isInlineSpecified() &&
2888 FD->getStorageClass() == SC_Extern);
2889}
2890
2891const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2892 const AttributedType *AT = T->getAs<AttributedType>();
2893 while (AT && !AT->isCallingConv())
2894 AT = AT->getModifiedType()->getAs<AttributedType>();
2895 return AT;
2896}
2897
2898template <typename T>
2899static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2900 const DeclContext *DC = Old->getDeclContext();
2901 if (DC->isRecord())
2902 return false;
2903
2904 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2905 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2906 return true;
2907 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2908 return true;
2909 return false;
2910}
2911
2912template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2913static bool isExternC(VarTemplateDecl *) { return false; }
2914
2915/// Check whether a redeclaration of an entity introduced by a
2916/// using-declaration is valid, given that we know it's not an overload
2917/// (nor a hidden tag declaration).
2918template<typename ExpectedDecl>
2919static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2920 ExpectedDecl *New) {
2921 // C++11 [basic.scope.declarative]p4:
2922 // Given a set of declarations in a single declarative region, each of
2923 // which specifies the same unqualified name,
2924 // -- they shall all refer to the same entity, or all refer to functions
2925 // and function templates; or
2926 // -- exactly one declaration shall declare a class name or enumeration
2927 // name that is not a typedef name and the other declarations shall all
2928 // refer to the same variable or enumerator, or all refer to functions
2929 // and function templates; in this case the class name or enumeration
2930 // name is hidden (3.3.10).
2931
2932 // C++11 [namespace.udecl]p14:
2933 // If a function declaration in namespace scope or block scope has the
2934 // same name and the same parameter-type-list as a function introduced
2935 // by a using-declaration, and the declarations do not declare the same
2936 // function, the program is ill-formed.
2937
2938 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2939 if (Old &&
2940 !Old->getDeclContext()->getRedeclContext()->Equals(
2941 New->getDeclContext()->getRedeclContext()) &&
2942 !(isExternC(Old) && isExternC(New)))
2943 Old = nullptr;
2944
2945 if (!Old) {
2946 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2947 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2948 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2949 return true;
2950 }
2951 return false;
2952}
2953
2954static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2955 const FunctionDecl *B) {
2956 assert(A->getNumParams() == B->getNumParams());
2957
2958 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2959 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2960 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2961 if (AttrA == AttrB)
2962 return true;
2963 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2964 AttrA->isDynamic() == AttrB->isDynamic();
2965 };
2966
2967 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2968}
2969
2970/// If necessary, adjust the semantic declaration context for a qualified
2971/// declaration to name the correct inline namespace within the qualifier.
2972static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2973 DeclaratorDecl *OldD) {
2974 // The only case where we need to update the DeclContext is when
2975 // redeclaration lookup for a qualified name finds a declaration
2976 // in an inline namespace within the context named by the qualifier:
2977 //
2978 // inline namespace N { int f(); }
2979 // int ::f(); // Sema DC needs adjusting from :: to N::.
2980 //
2981 // For unqualified declarations, the semantic context *can* change
2982 // along the redeclaration chain (for local extern declarations,
2983 // extern "C" declarations, and friend declarations in particular).
2984 if (!NewD->getQualifier())
2985 return;
2986
2987 // NewD is probably already in the right context.
2988 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2989 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2990 if (NamedDC->Equals(SemaDC))
2991 return;
2992
2993 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2994 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2995 "unexpected context for redeclaration");
2996
2997 auto *LexDC = NewD->getLexicalDeclContext();
2998 auto FixSemaDC = [=](NamedDecl *D) {
2999 if (!D)
3000 return;
3001 D->setDeclContext(SemaDC);
3002 D->setLexicalDeclContext(LexDC);
3003 };
3004
3005 FixSemaDC(NewD);
3006 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3007 FixSemaDC(FD->getDescribedFunctionTemplate());
3008 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3009 FixSemaDC(VD->getDescribedVarTemplate());
3010}
3011
3012/// MergeFunctionDecl - We just parsed a function 'New' from
3013/// declarator D which has the same name and scope as a previous
3014/// declaration 'Old'. Figure out how to resolve this situation,
3015/// merging decls or emitting diagnostics as appropriate.
3016///
3017/// In C++, New and Old must be declarations that are not
3018/// overloaded. Use IsOverload to determine whether New and Old are
3019/// overloaded, and to select the Old declaration that New should be
3020/// merged with.
3021///
3022/// Returns true if there was an error, false otherwise.
3023bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3024 Scope *S, bool MergeTypeWithOld) {
3025 // Verify the old decl was also a function.
3026 FunctionDecl *Old = OldD->getAsFunction();
3027 if (!Old) {
3028 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3029 if (New->getFriendObjectKind()) {
3030 Diag(New->getLocation(), diag::err_using_decl_friend);
3031 Diag(Shadow->getTargetDecl()->getLocation(),
3032 diag::note_using_decl_target);
3033 Diag(Shadow->getUsingDecl()->getLocation(),
3034 diag::note_using_decl) << 0;
3035 return true;
3036 }
3037
3038 // Check whether the two declarations might declare the same function.
3039 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3040 return true;
3041 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3042 } else {
3043 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3044 << New->getDeclName();
3045 notePreviousDefinition(OldD, New->getLocation());
3046 return true;
3047 }
3048 }
3049
3050 // If the old declaration is invalid, just give up here.
3051 if (Old->isInvalidDecl())
3052 return true;
3053
3054 // Disallow redeclaration of some builtins.
3055 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3056 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3057 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3058 << Old << Old->getType();
3059 return true;
3060 }
3061
3062 diag::kind PrevDiag;
3063 SourceLocation OldLocation;
3064 std::tie(PrevDiag, OldLocation) =
3065 getNoteDiagForInvalidRedeclaration(Old, New);
3066
3067 // Don't complain about this if we're in GNU89 mode and the old function
3068 // is an extern inline function.
3069 // Don't complain about specializations. They are not supposed to have
3070 // storage classes.
3071 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3072 New->getStorageClass() == SC_Static &&
3073 Old->hasExternalFormalLinkage() &&
3074 !New->getTemplateSpecializationInfo() &&
3075 !canRedefineFunction(Old, getLangOpts())) {
3076 if (getLangOpts().MicrosoftExt) {
3077 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3078 Diag(OldLocation, PrevDiag);
3079 } else {
3080 Diag(New->getLocation(), diag::err_static_non_static) << New;
3081 Diag(OldLocation, PrevDiag);
3082 return true;
3083 }
3084 }
3085
3086 if (New->hasAttr<InternalLinkageAttr>() &&
3087 !Old->hasAttr<InternalLinkageAttr>()) {
3088 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3089 << New->getDeclName();
3090 notePreviousDefinition(Old, New->getLocation());
3091 New->dropAttr<InternalLinkageAttr>();
3092 }
3093
3094 if (CheckRedeclarationModuleOwnership(New, Old))
3095 return true;
3096
3097 if (!getLangOpts().CPlusPlus) {
3098 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3099 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3100 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3101 << New << OldOvl;
3102
3103 // Try our best to find a decl that actually has the overloadable
3104 // attribute for the note. In most cases (e.g. programs with only one
3105 // broken declaration/definition), this won't matter.
3106 //
3107 // FIXME: We could do this if we juggled some extra state in
3108 // OverloadableAttr, rather than just removing it.
3109 const Decl *DiagOld = Old;
3110 if (OldOvl) {
3111 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3112 const auto *A = D->getAttr<OverloadableAttr>();
3113 return A && !A->isImplicit();
3114 });
3115 // If we've implicitly added *all* of the overloadable attrs to this
3116 // chain, emitting a "previous redecl" note is pointless.
3117 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3118 }
3119
3120 if (DiagOld)
3121 Diag(DiagOld->getLocation(),
3122 diag::note_attribute_overloadable_prev_overload)
3123 << OldOvl;
3124
3125 if (OldOvl)
3126 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3127 else
3128 New->dropAttr<OverloadableAttr>();
3129 }
3130 }
3131
3132 // If a function is first declared with a calling convention, but is later
3133 // declared or defined without one, all following decls assume the calling
3134 // convention of the first.
3135 //
3136 // It's OK if a function is first declared without a calling convention,
3137 // but is later declared or defined with the default calling convention.
3138 //
3139 // To test if either decl has an explicit calling convention, we look for
3140 // AttributedType sugar nodes on the type as written. If they are missing or
3141 // were canonicalized away, we assume the calling convention was implicit.
3142 //
3143 // Note also that we DO NOT return at this point, because we still have
3144 // other tests to run.
3145 QualType OldQType = Context.getCanonicalType(Old->getType());
3146 QualType NewQType = Context.getCanonicalType(New->getType());
3147 const FunctionType *OldType = cast<FunctionType>(OldQType);
3148 const FunctionType *NewType = cast<FunctionType>(NewQType);
3149 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3150 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3151 bool RequiresAdjustment = false;
3152
3153 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3154 FunctionDecl *First = Old->getFirstDecl();
3155 const FunctionType *FT =
3156 First->getType().getCanonicalType()->castAs<FunctionType>();
3157 FunctionType::ExtInfo FI = FT->getExtInfo();
3158 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3159 if (!NewCCExplicit) {
3160 // Inherit the CC from the previous declaration if it was specified
3161 // there but not here.
3162 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3163 RequiresAdjustment = true;
3164 } else if (New->getBuiltinID()) {
3165 // Calling Conventions on a Builtin aren't really useful and setting a
3166 // default calling convention and cdecl'ing some builtin redeclarations is
3167 // common, so warn and ignore the calling convention on the redeclaration.
3168 Diag(New->getLocation(), diag::warn_cconv_ignored)
3169 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3170 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3171 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3172 RequiresAdjustment = true;
3173 } else {
3174 // Calling conventions aren't compatible, so complain.
3175 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3176 Diag(New->getLocation(), diag::err_cconv_change)
3177 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3178 << !FirstCCExplicit
3179 << (!FirstCCExplicit ? "" :
3180 FunctionType::getNameForCallConv(FI.getCC()));
3181
3182 // Put the note on the first decl, since it is the one that matters.
3183 Diag(First->getLocation(), diag::note_previous_declaration);
3184 return true;
3185 }
3186 }
3187
3188 // FIXME: diagnose the other way around?
3189 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3190 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3191 RequiresAdjustment = true;
3192 }
3193
3194 // Merge regparm attribute.
3195 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3196 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3197 if (NewTypeInfo.getHasRegParm()) {
3198 Diag(New->getLocation(), diag::err_regparm_mismatch)
3199 << NewType->getRegParmType()
3200 << OldType->getRegParmType();
3201 Diag(OldLocation, diag::note_previous_declaration);
3202 return true;
3203 }
3204
3205 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3206 RequiresAdjustment = true;
3207 }
3208
3209 // Merge ns_returns_retained attribute.
3210 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3211 if (NewTypeInfo.getProducesResult()) {
3212 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3213 << "'ns_returns_retained'";
3214 Diag(OldLocation, diag::note_previous_declaration);
3215 return true;
3216 }
3217
3218 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3219 RequiresAdjustment = true;
3220 }
3221
3222 if (OldTypeInfo.getNoCallerSavedRegs() !=
3223 NewTypeInfo.getNoCallerSavedRegs()) {
3224 if (NewTypeInfo.getNoCallerSavedRegs()) {
3225 AnyX86NoCallerSavedRegistersAttr *Attr =
3226 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3227 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3228 Diag(OldLocation, diag::note_previous_declaration);
3229 return true;
3230 }
3231
3232 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3233 RequiresAdjustment = true;
3234 }
3235
3236 if (RequiresAdjustment) {
3237 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3238 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3239 New->setType(QualType(AdjustedType, 0));
3240 NewQType = Context.getCanonicalType(New->getType());
3241 NewType = cast<FunctionType>(NewQType);
3242 }
3243
3244 // If this redeclaration makes the function inline, we may need to add it to
3245 // UndefinedButUsed.
3246 if (!Old->isInlined() && New->isInlined() &&
3247 !New->hasAttr<GNUInlineAttr>() &&
3248 !getLangOpts().GNUInline &&
3249 Old->isUsed(false) &&
3250 !Old->isDefined() && !New->isThisDeclarationADefinition())
3251 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3252 SourceLocation()));
3253
3254 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3255 // about it.
3256 if (New->hasAttr<GNUInlineAttr>() &&
3257 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3258 UndefinedButUsed.erase(Old->getCanonicalDecl());
3259 }
3260
3261 // If pass_object_size params don't match up perfectly, this isn't a valid
3262 // redeclaration.
3263 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3264 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3265 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3266 << New->getDeclName();
3267 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3268 return true;
3269 }
3270
3271 if (getLangOpts().CPlusPlus) {
3272 // C++1z [over.load]p2
3273 // Certain function declarations cannot be overloaded:
3274 // -- Function declarations that differ only in the return type,
3275 // the exception specification, or both cannot be overloaded.
3276
3277 // Check the exception specifications match. This may recompute the type of
3278 // both Old and New if it resolved exception specifications, so grab the
3279 // types again after this. Because this updates the type, we do this before
3280 // any of the other checks below, which may update the "de facto" NewQType
3281 // but do not necessarily update the type of New.
3282 if (CheckEquivalentExceptionSpec(Old, New))
3283 return true;
3284 OldQType = Context.getCanonicalType(Old->getType());
3285 NewQType = Context.getCanonicalType(New->getType());
3286
3287 // Go back to the type source info to compare the declared return types,
3288 // per C++1y [dcl.type.auto]p13:
3289 // Redeclarations or specializations of a function or function template
3290 // with a declared return type that uses a placeholder type shall also
3291 // use that placeholder, not a deduced type.
3292 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3293 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3294 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3295 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3296 OldDeclaredReturnType)) {
3297 QualType ResQT;
3298 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3299 OldDeclaredReturnType->isObjCObjectPointerType())
3300 // FIXME: This does the wrong thing for a deduced return type.
3301 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3302 if (ResQT.isNull()) {
3303 if (New->isCXXClassMember() && New->isOutOfLine())
3304 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3305 << New << New->getReturnTypeSourceRange();
3306 else
3307 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3308 << New->getReturnTypeSourceRange();
3309 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3310 << Old->getReturnTypeSourceRange();
3311 return true;
3312 }
3313 else
3314 NewQType = ResQT;
3315 }
3316
3317 QualType OldReturnType = OldType->getReturnType();
3318 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3319 if (OldReturnType != NewReturnType) {
3320 // If this function has a deduced return type and has already been
3321 // defined, copy the deduced value from the old declaration.
3322 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3323 if (OldAT && OldAT->isDeduced()) {
3324 New->setType(
3325 SubstAutoType(New->getType(),
3326 OldAT->isDependentType() ? Context.DependentTy
3327 : OldAT->getDeducedType()));
3328 NewQType = Context.getCanonicalType(
3329 SubstAutoType(NewQType,
3330 OldAT->isDependentType() ? Context.DependentTy
3331 : OldAT->getDeducedType()));
3332 }
3333 }
3334
3335 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3336 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3337 if (OldMethod && NewMethod) {
3338 // Preserve triviality.
3339 NewMethod->setTrivial(OldMethod->isTrivial());
3340
3341 // MSVC allows explicit template specialization at class scope:
3342 // 2 CXXMethodDecls referring to the same function will be injected.
3343 // We don't want a redeclaration error.
3344 bool IsClassScopeExplicitSpecialization =
3345 OldMethod->isFunctionTemplateSpecialization() &&
3346 NewMethod->isFunctionTemplateSpecialization();
3347 bool isFriend = NewMethod->getFriendObjectKind();
3348
3349 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3350 !IsClassScopeExplicitSpecialization) {
3351 // -- Member function declarations with the same name and the
3352 // same parameter types cannot be overloaded if any of them
3353 // is a static member function declaration.
3354 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3355 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3356 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3357 return true;
3358 }
3359
3360 // C++ [class.mem]p1:
3361 // [...] A member shall not be declared twice in the
3362 // member-specification, except that a nested class or member
3363 // class template can be declared and then later defined.
3364 if (!inTemplateInstantiation()) {
3365 unsigned NewDiag;
3366 if (isa<CXXConstructorDecl>(OldMethod))
3367 NewDiag = diag::err_constructor_redeclared;
3368 else if (isa<CXXDestructorDecl>(NewMethod))
3369 NewDiag = diag::err_destructor_redeclared;
3370 else if (isa<CXXConversionDecl>(NewMethod))
3371 NewDiag = diag::err_conv_function_redeclared;
3372 else
3373 NewDiag = diag::err_member_redeclared;
3374
3375 Diag(New->getLocation(), NewDiag);
3376 } else {
3377 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3378 << New << New->getType();
3379 }
3380 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3381 return true;
3382
3383 // Complain if this is an explicit declaration of a special
3384 // member that was initially declared implicitly.
3385 //
3386 // As an exception, it's okay to befriend such methods in order
3387 // to permit the implicit constructor/destructor/operator calls.
3388 } else if (OldMethod->isImplicit()) {
3389 if (isFriend) {
3390 NewMethod->setImplicit();
3391 } else {
3392 Diag(NewMethod->getLocation(),
3393 diag::err_definition_of_implicitly_declared_member)
3394 << New << getSpecialMember(OldMethod);
3395 return true;
3396 }
3397 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3398 Diag(NewMethod->getLocation(),
3399 diag::err_definition_of_explicitly_defaulted_member)
3400 << getSpecialMember(OldMethod);
3401 return true;
3402 }
3403 }
3404
3405 // C++11 [dcl.attr.noreturn]p1:
3406 // The first declaration of a function shall specify the noreturn
3407 // attribute if any declaration of that function specifies the noreturn
3408 // attribute.
3409 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3410 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3411 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3412 Diag(Old->getFirstDecl()->getLocation(),
3413 diag::note_noreturn_missing_first_decl);
3414 }
3415
3416 // C++11 [dcl.attr.depend]p2:
3417 // The first declaration of a function shall specify the
3418 // carries_dependency attribute for its declarator-id if any declaration
3419 // of the function specifies the carries_dependency attribute.
3420 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3421 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3422 Diag(CDA->getLocation(),
3423 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3424 Diag(Old->getFirstDecl()->getLocation(),
3425 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3426 }
3427
3428 // (C++98 8.3.5p3):
3429 // All declarations for a function shall agree exactly in both the
3430 // return type and the parameter-type-list.
3431 // We also want to respect all the extended bits except noreturn.
3432
3433 // noreturn should now match unless the old type info didn't have it.
3434 QualType OldQTypeForComparison = OldQType;
3435 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3436 auto *OldType = OldQType->castAs<FunctionProtoType>();
3437 const FunctionType *OldTypeForComparison
3438 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3439 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3440 assert(OldQTypeForComparison.isCanonical());
3441 }
3442
3443 if (haveIncompatibleLanguageLinkages(Old, New)) {
3444 // As a special case, retain the language linkage from previous
3445 // declarations of a friend function as an extension.
3446 //
3447 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3448 // and is useful because there's otherwise no way to specify language
3449 // linkage within class scope.
3450 //
3451 // Check cautiously as the friend object kind isn't yet complete.
3452 if (New->getFriendObjectKind() != Decl::FOK_None) {
3453 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3454 Diag(OldLocation, PrevDiag);
3455 } else {
3456 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3457 Diag(OldLocation, PrevDiag);
3458 return true;
3459 }
3460 }
3461
3462 if (OldQTypeForComparison == NewQType)
3463 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3464
3465 // If the types are imprecise (due to dependent constructs in friends or
3466 // local extern declarations), it's OK if they differ. We'll check again
3467 // during instantiation.
3468 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3469 return false;
3470
3471 // Fall through for conflicting redeclarations and redefinitions.
3472 }
3473
3474 // C: Function types need to be compatible, not identical. This handles
3475 // duplicate function decls like "void f(int); void f(enum X);" properly.
3476 if (!getLangOpts().CPlusPlus &&
3477 Context.typesAreCompatible(OldQType, NewQType)) {
3478 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3479 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3480 const FunctionProtoType *OldProto = nullptr;
3481 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3482 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3483 // The old declaration provided a function prototype, but the
3484 // new declaration does not. Merge in the prototype.
3485 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3486 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3487 NewQType =
3488 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3489 OldProto->getExtProtoInfo());
3490 New->setType(NewQType);
3491 New->setHasInheritedPrototype();
3492
3493 // Synthesize parameters with the same types.
3494 SmallVector<ParmVarDecl*, 16> Params;
3495 for (const auto &ParamType : OldProto->param_types()) {
3496 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3497 SourceLocation(), nullptr,
3498 ParamType, /*TInfo=*/nullptr,
3499 SC_None, nullptr);
3500 Param->setScopeInfo(0, Params.size());
3501 Param->setImplicit();
3502 Params.push_back(Param);
3503 }
3504
3505 New->setParams(Params);
3506 }
3507
3508 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3509 }
3510
3511 // GNU C permits a K&R definition to follow a prototype declaration
3512 // if the declared types of the parameters in the K&R definition
3513 // match the types in the prototype declaration, even when the
3514 // promoted types of the parameters from the K&R definition differ
3515 // from the types in the prototype. GCC then keeps the types from
3516 // the prototype.
3517 //
3518 // If a variadic prototype is followed by a non-variadic K&R definition,
3519 // the K&R definition becomes variadic. This is sort of an edge case, but
3520 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3521 // C99 6.9.1p8.
3522 if (!getLangOpts().CPlusPlus &&
3523 Old->hasPrototype() && !New->hasPrototype() &&
3524 New->getType()->getAs<FunctionProtoType>() &&
3525 Old->getNumParams() == New->getNumParams()) {
3526 SmallVector<QualType, 16> ArgTypes;
3527 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3528 const FunctionProtoType *OldProto
3529 = Old->getType()->getAs<FunctionProtoType>();
3530 const FunctionProtoType *NewProto
3531 = New->getType()->getAs<FunctionProtoType>();
3532
3533 // Determine whether this is the GNU C extension.
3534 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3535 NewProto->getReturnType());
3536 bool LooseCompatible = !MergedReturn.isNull();
3537 for (unsigned Idx = 0, End = Old->getNumParams();
3538 LooseCompatible && Idx != End; ++Idx) {
3539 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3540 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3541 if (Context.typesAreCompatible(OldParm->getType(),
3542 NewProto->getParamType(Idx))) {
3543 ArgTypes.push_back(NewParm->getType());
3544 } else if (Context.typesAreCompatible(OldParm->getType(),
3545 NewParm->getType(),
3546 /*CompareUnqualified=*/true)) {
3547 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3548 NewProto->getParamType(Idx) };
3549 Warnings.push_back(Warn);
3550 ArgTypes.push_back(NewParm->getType());
3551 } else
3552 LooseCompatible = false;
3553 }
3554
3555 if (LooseCompatible) {
3556 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3557 Diag(Warnings[Warn].NewParm->getLocation(),
3558 diag::ext_param_promoted_not_compatible_with_prototype)
3559 << Warnings[Warn].PromotedType
3560 << Warnings[Warn].OldParm->getType();
3561 if (Warnings[Warn].OldParm->getLocation().isValid())
3562 Diag(Warnings[Warn].OldParm->getLocation(),
3563 diag::note_previous_declaration);
3564 }
3565
3566 if (MergeTypeWithOld)
3567 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3568 OldProto->getExtProtoInfo()));
3569 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3570 }
3571
3572 // Fall through to diagnose conflicting types.
3573 }
3574
3575 // A function that has already been declared has been redeclared or
3576 // defined with a different type; show an appropriate diagnostic.
3577
3578 // If the previous declaration was an implicitly-generated builtin
3579 // declaration, then at the very least we should use a specialized note.
3580 unsigned BuiltinID;
3581 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3582 // If it's actually a library-defined builtin function like 'malloc'
3583 // or 'printf', just warn about the incompatible redeclaration.
3584 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3585 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3586 Diag(OldLocation, diag::note_previous_builtin_declaration)
3587 << Old << Old->getType();
3588
3589 // If this is a global redeclaration, just forget hereafter
3590 // about the "builtin-ness" of the function.
3591 //
3592 // Doing this for local extern declarations is problematic. If
3593 // the builtin declaration remains visible, a second invalid
3594 // local declaration will produce a hard error; if it doesn't
3595 // remain visible, a single bogus local redeclaration (which is
3596 // actually only a warning) could break all the downstream code.
3597 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3598 New->getIdentifier()->revertBuiltin();
3599
3600 return false;
3601 }
3602
3603 PrevDiag = diag::note_previous_builtin_declaration;
3604 }
3605
3606 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3607 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3608 return true;
3609}
3610
3611/// Completes the merge of two function declarations that are
3612/// known to be compatible.
3613///
3614/// This routine handles the merging of attributes and other
3615/// properties of function declarations from the old declaration to
3616/// the new declaration, once we know that New is in fact a
3617/// redeclaration of Old.
3618///
3619/// \returns false
3620bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3621 Scope *S, bool MergeTypeWithOld) {
3622 // Merge the attributes
3623 mergeDeclAttributes(New, Old);
3624
3625 // Merge "pure" flag.
3626 if (Old->isPure())
3627 New->setPure();
3628
3629 // Merge "used" flag.
3630 if (Old->getMostRecentDecl()->isUsed(false))
3631 New->setIsUsed();
3632
3633 // Merge attributes from the parameters. These can mismatch with K&R
3634 // declarations.
3635 if (New->getNumParams() == Old->getNumParams())
3636 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3637 ParmVarDecl *NewParam = New->getParamDecl(i);
3638 ParmVarDecl *OldParam = Old->getParamDecl(i);
3639 mergeParamDeclAttributes(NewParam, OldParam, *this);
3640 mergeParamDeclTypes(NewParam, OldParam, *this);
3641 }
3642
3643 if (getLangOpts().CPlusPlus)
3644 return MergeCXXFunctionDecl(New, Old, S);
3645
3646 // Merge the function types so the we get the composite types for the return
3647 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3648 // was visible.
3649 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3650 if (!Merged.isNull() && MergeTypeWithOld)
3651 New->setType(Merged);
3652
3653 return false;
3654}
3655
3656void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3657 ObjCMethodDecl *oldMethod) {
3658 // Merge the attributes, including deprecated/unavailable
3659 AvailabilityMergeKind MergeKind =
3660 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3661 ? AMK_ProtocolImplementation
3662 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3663 : AMK_Override;
3664
3665 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3666
3667 // Merge attributes from the parameters.
3668 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3669 oe = oldMethod->param_end();
3670 for (ObjCMethodDecl::param_iterator
3671 ni = newMethod->param_begin(), ne = newMethod->param_end();
3672 ni != ne && oi != oe; ++ni, ++oi)
3673 mergeParamDeclAttributes(*ni, *oi, *this);
3674
3675 CheckObjCMethodOverride(newMethod, oldMethod);
3676}
3677
3678static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3679 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3680
3681 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3682 ? diag::err_redefinition_different_type
3683 : diag::err_redeclaration_different_type)
3684 << New->getDeclName() << New->getType() << Old->getType();
3685
3686 diag::kind PrevDiag;
3687 SourceLocation OldLocation;
3688 std::tie(PrevDiag, OldLocation)
3689 = getNoteDiagForInvalidRedeclaration(Old, New);
3690 S.Diag(OldLocation, PrevDiag);
3691 New->setInvalidDecl();
3692}
3693
3694/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3695/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3696/// emitting diagnostics as appropriate.
3697///
3698/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3699/// to here in AddInitializerToDecl. We can't check them before the initializer
3700/// is attached.
3701void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3702 bool MergeTypeWithOld) {
3703 if (New->isInvalidDecl() || Old->isInvalidDecl())
3704 return;
3705
3706 QualType MergedT;
3707 if (getLangOpts().CPlusPlus) {
3708 if (New->getType()->isUndeducedType()) {
3709 // We don't know what the new type is until the initializer is attached.
3710 return;
3711 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3712 // These could still be something that needs exception specs checked.
3713 return MergeVarDeclExceptionSpecs(New, Old);
3714 }
3715 // C++ [basic.link]p10:
3716 // [...] the types specified by all declarations referring to a given
3717 // object or function shall be identical, except that declarations for an
3718 // array object can specify array types that differ by the presence or
3719 // absence of a major array bound (8.3.4).
3720 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3721 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3722 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3723
3724 // We are merging a variable declaration New into Old. If it has an array
3725 // bound, and that bound differs from Old's bound, we should diagnose the
3726 // mismatch.
3727 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3728 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3729 PrevVD = PrevVD->getPreviousDecl()) {
3730 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3731 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3732 continue;
3733
3734 if (!Context.hasSameType(NewArray, PrevVDTy))
3735 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3736 }
3737 }
3738
3739 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3740 if (Context.hasSameType(OldArray->getElementType(),
3741 NewArray->getElementType()))
3742 MergedT = New->getType();
3743 }
3744 // FIXME: Check visibility. New is hidden but has a complete type. If New
3745 // has no array bound, it should not inherit one from Old, if Old is not
3746 // visible.
3747 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3748 if (Context.hasSameType(OldArray->getElementType(),
3749 NewArray->getElementType()))
3750 MergedT = Old->getType();
3751 }
3752 }
3753 else if (New->getType()->isObjCObjectPointerType() &&
3754 Old->getType()->isObjCObjectPointerType()) {
3755 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3756 Old->getType());
3757 }
3758 } else {
3759 // C 6.2.7p2:
3760 // All declarations that refer to the same object or function shall have
3761 // compatible type.
3762 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3763 }
3764 if (MergedT.isNull()) {
3765 // It's OK if we couldn't merge types if either type is dependent, for a
3766 // block-scope variable. In other cases (static data members of class
3767 // templates, variable templates, ...), we require the types to be
3768 // equivalent.
3769 // FIXME: The C++ standard doesn't say anything about this.
3770 if ((New->getType()->isDependentType() ||
3771 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3772 // If the old type was dependent, we can't merge with it, so the new type
3773 // becomes dependent for now. We'll reproduce the original type when we
3774 // instantiate the TypeSourceInfo for the variable.
3775 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3776 New->setType(Context.DependentTy);
3777 return;
3778 }
3779 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3780 }
3781
3782 // Don't actually update the type on the new declaration if the old
3783 // declaration was an extern declaration in a different scope.
3784 if (MergeTypeWithOld)
3785 New->setType(MergedT);
3786}
3787
3788static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3789 LookupResult &Previous) {
3790 // C11 6.2.7p4:
3791 // For an identifier with internal or external linkage declared
3792 // in a scope in which a prior declaration of that identifier is
3793 // visible, if the prior declaration specifies internal or
3794 // external linkage, the type of the identifier at the later
3795 // declaration becomes the composite type.
3796 //
3797 // If the variable isn't visible, we do not merge with its type.
3798 if (Previous.isShadowed())
3799 return false;
3800
3801 if (S.getLangOpts().CPlusPlus) {
3802 // C++11 [dcl.array]p3:
3803 // If there is a preceding declaration of the entity in the same
3804 // scope in which the bound was specified, an omitted array bound
3805 // is taken to be the same as in that earlier declaration.
3806 return NewVD->isPreviousDeclInSameBlockScope() ||
3807 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3808 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3809 } else {
3810 // If the old declaration was function-local, don't merge with its
3811 // type unless we're in the same function.
3812 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3813 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3814 }
3815}
3816
3817/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3818/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3819/// situation, merging decls or emitting diagnostics as appropriate.
3820///
3821/// Tentative definition rules (C99 6.9.2p2) are checked by
3822/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3823/// definitions here, since the initializer hasn't been attached.
3824///
3825void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3826 // If the new decl is already invalid, don't do any other checking.
3827 if (New->isInvalidDecl())
3828 return;
3829
3830 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3831 return;
3832
3833 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3834
3835 // Verify the old decl was also a variable or variable template.
3836 VarDecl *Old = nullptr;
3837 VarTemplateDecl *OldTemplate = nullptr;
3838 if (Previous.isSingleResult()) {
3839 if (NewTemplate) {
3840 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3841 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3842
3843 if (auto *Shadow =
3844 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3845 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3846 return New->setInvalidDecl();
3847 } else {
3848 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3849
3850 if (auto *Shadow =
3851 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3852 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3853 return New->setInvalidDecl();
3854 }
3855 }
3856 if (!Old) {
3857 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3858 << New->getDeclName();
3859 notePreviousDefinition(Previous.getRepresentativeDecl(),
3860 New->getLocation());
3861 return New->setInvalidDecl();
3862 }
3863
3864 // Ensure the template parameters are compatible.
3865 if (NewTemplate &&
3866 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3867 OldTemplate->getTemplateParameters(),
3868 /*Complain=*/true, TPL_TemplateMatch))
3869 return New->setInvalidDecl();
3870
3871 // C++ [class.mem]p1:
3872 // A member shall not be declared twice in the member-specification [...]
3873 //
3874 // Here, we need only consider static data members.
3875 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3876 Diag(New->getLocation(), diag::err_duplicate_member)
3877 << New->getIdentifier();
3878 Diag(Old->getLocation(), diag::note_previous_declaration);
3879 New->setInvalidDecl();
3880 }
3881
3882 mergeDeclAttributes(New, Old);
3883 // Warn if an already-declared variable is made a weak_import in a subsequent
3884 // declaration
3885 if (New->hasAttr<WeakImportAttr>() &&
3886 Old->getStorageClass() == SC_None &&
3887 !Old->hasAttr<WeakImportAttr>()) {
3888 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3889 notePreviousDefinition(Old, New->getLocation());
3890 // Remove weak_import attribute on new declaration.
3891 New->dropAttr<WeakImportAttr>();
3892 }
3893
3894 if (New->hasAttr<InternalLinkageAttr>() &&
3895 !Old->hasAttr<InternalLinkageAttr>()) {
3896 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3897 << New->getDeclName();
3898 notePreviousDefinition(Old, New->getLocation());
3899 New->dropAttr<InternalLinkageAttr>();
3900 }
3901
3902 // Merge the types.
3903 VarDecl *MostRecent = Old->getMostRecentDecl();
3904 if (MostRecent != Old) {
3905 MergeVarDeclTypes(New, MostRecent,
3906 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3907 if (New->isInvalidDecl())
3908 return;
3909 }
3910
3911 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3912 if (New->isInvalidDecl())
3913 return;
3914
3915 diag::kind PrevDiag;
3916 SourceLocation OldLocation;
3917 std::tie(PrevDiag, OldLocation) =
3918 getNoteDiagForInvalidRedeclaration(Old, New);
3919
3920 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3921 if (New->getStorageClass() == SC_Static &&
3922 !New->isStaticDataMember() &&
3923 Old->hasExternalFormalLinkage()) {
3924 if (getLangOpts().MicrosoftExt) {
3925 Diag(New->getLocation(), diag::ext_static_non_static)
3926 << New->getDeclName();
3927 Diag(OldLocation, PrevDiag);
3928 } else {
3929 Diag(New->getLocation(), diag::err_static_non_static)
3930 << New->getDeclName();
3931 Diag(OldLocation, PrevDiag);
3932 return New->setInvalidDecl();
3933 }
3934 }
3935 // C99 6.2.2p4:
3936 // For an identifier declared with the storage-class specifier
3937 // extern in a scope in which a prior declaration of that
3938 // identifier is visible,23) if the prior declaration specifies
3939 // internal or external linkage, the linkage of the identifier at
3940 // the later declaration is the same as the linkage specified at
3941 // the prior declaration. If no prior declaration is visible, or
3942 // if the prior declaration specifies no linkage, then the
3943 // identifier has external linkage.
3944 if (New->hasExternalStorage() && Old->hasLinkage())
3945 /* Okay */;
3946 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3947 !New->isStaticDataMember() &&
3948 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3949 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3950 Diag(OldLocation, PrevDiag);
3951 return New->setInvalidDecl();
3952 }
3953
3954 // Check if extern is followed by non-extern and vice-versa.
3955 if (New->hasExternalStorage() &&
3956 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3957 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3958 Diag(OldLocation, PrevDiag);
3959 return New->setInvalidDecl();
3960 }
3961 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3962 !New->hasExternalStorage()) {
3963 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3964 Diag(OldLocation, PrevDiag);
3965 return New->setInvalidDecl();
3966 }
3967
3968 if (CheckRedeclarationModuleOwnership(New, Old))
3969 return;
3970
3971 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3972
3973 // FIXME: The test for external storage here seems wrong? We still
3974 // need to check for mismatches.
3975 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3976 // Don't complain about out-of-line definitions of static members.
3977 !(Old->getLexicalDeclContext()->isRecord() &&
3978 !New->getLexicalDeclContext()->isRecord())) {
3979 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3980 Diag(OldLocation, PrevDiag);
3981 return New->setInvalidDecl();
3982 }
3983
3984 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3985 if (VarDecl *Def = Old->getDefinition()) {
3986 // C++1z [dcl.fcn.spec]p4:
3987 // If the definition of a variable appears in a translation unit before
3988 // its first declaration as inline, the program is ill-formed.
3989 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3990 Diag(Def->getLocation(), diag::note_previous_definition);
3991 }
3992 }
3993
3994 // If this redeclaration makes the variable inline, we may need to add it to
3995 // UndefinedButUsed.
3996 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3997 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3998 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3999 SourceLocation()));
4000
4001 if (New->getTLSKind() != Old->getTLSKind()) {
4002 if (!Old->getTLSKind()) {
4003 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4004 Diag(OldLocation, PrevDiag);
4005 } else if (!New->getTLSKind()) {
4006 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4007 Diag(OldLocation, PrevDiag);
4008 } else {
4009 // Do not allow redeclaration to change the variable between requiring
4010 // static and dynamic initialization.
4011 // FIXME: GCC allows this, but uses the TLS keyword on the first
4012 // declaration to determine the kind. Do we need to be compatible here?
4013 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4014 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4015 Diag(OldLocation, PrevDiag);
4016 }
4017 }
4018
4019 // C++ doesn't have tentative definitions, so go right ahead and check here.
4020 if (getLangOpts().CPlusPlus &&
4021 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4022 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4023 Old->getCanonicalDecl()->isConstexpr()) {
4024 // This definition won't be a definition any more once it's been merged.
4025 Diag(New->getLocation(),
4026 diag::warn_deprecated_redundant_constexpr_static_def);
4027 } else if (VarDecl *Def = Old->getDefinition()) {
4028 if (checkVarDeclRedefinition(Def, New))
4029 return;
4030 }
4031 }
4032
4033 if (haveIncompatibleLanguageLinkages(Old, New)) {
4034 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4035 Diag(OldLocation, PrevDiag);
4036 New->setInvalidDecl();
4037 return;
4038 }
4039
4040 // Merge "used" flag.
4041 if (Old->getMostRecentDecl()->isUsed(false))
4042 New->setIsUsed();
4043
4044 // Keep a chain of previous declarations.
4045 New->setPreviousDecl(Old);
4046 if (NewTemplate)
4047 NewTemplate->setPreviousDecl(OldTemplate);
4048 adjustDeclContextForDeclaratorDecl(New, Old);
4049
4050 // Inherit access appropriately.
4051 New->setAccess(Old->getAccess());
4052 if (NewTemplate)
4053 NewTemplate->setAccess(New->getAccess());
4054
4055 if (Old->isInline())
4056 New->setImplicitlyInline();
4057}
4058
4059void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4060 SourceManager &SrcMgr = getSourceManager();
4061 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4062 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4063 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4064 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4065 auto &HSI = PP.getHeaderSearchInfo();
4066 StringRef HdrFilename =
4067 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4068
4069 auto noteFromModuleOrInclude = [&](Module *Mod,
4070 SourceLocation IncLoc) -> bool {
4071 // Redefinition errors with modules are common with non modular mapped
4072 // headers, example: a non-modular header H in module A that also gets
4073 // included directly in a TU. Pointing twice to the same header/definition
4074 // is confusing, try to get better diagnostics when modules is on.
4075 if (IncLoc.isValid()) {
4076 if (Mod) {
4077 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4078 << HdrFilename.str() << Mod->getFullModuleName();
4079 if (!Mod->DefinitionLoc.isInvalid())
4080 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4081 << Mod->getFullModuleName();
4082 } else {
4083 Diag(IncLoc, diag::note_redefinition_include_same_file)
4084 << HdrFilename.str();
4085 }
4086 return true;
4087 }
4088
4089 return false;
4090 };
4091
4092 // Is it the same file and same offset? Provide more information on why
4093 // this leads to a redefinition error.
4094 bool EmittedDiag = false;
4095 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4096 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4097 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4098 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4099 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4100
4101 // If the header has no guards, emit a note suggesting one.
4102 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4103 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4104
4105 if (EmittedDiag)
4106 return;
4107 }
4108
4109 // Redefinition coming from different files or couldn't do better above.
4110 if (Old->getLocation().isValid())
4111 Diag(Old->getLocation(), diag::note_previous_definition);
4112}
4113
4114/// We've just determined that \p Old and \p New both appear to be definitions
4115/// of the same variable. Either diagnose or fix the problem.
4116bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4117 if (!hasVisibleDefinition(Old) &&
4118 (New->getFormalLinkage() == InternalLinkage ||
4119 New->isInline() ||
4120 New->getDescribedVarTemplate() ||
4121 New->getNumTemplateParameterLists() ||
4122 New->getDeclContext()->isDependentContext())) {
4123 // The previous definition is hidden, and multiple definitions are
4124 // permitted (in separate TUs). Demote this to a declaration.
4125 New->demoteThisDefinitionToDeclaration();
4126
4127 // Make the canonical definition visible.
4128 if (auto *OldTD = Old->getDescribedVarTemplate())
4129 makeMergedDefinitionVisible(OldTD);
4130 makeMergedDefinitionVisible(Old);
4131 return false;
4132 } else {
4133 Diag(New->getLocation(), diag::err_redefinition) << New;
4134 notePreviousDefinition(Old, New->getLocation());
4135 New->setInvalidDecl();
4136 return true;
4137 }
4138}
4139
4140/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4141/// no declarator (e.g. "struct foo;") is parsed.
4142Decl *
4143Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4144 RecordDecl *&AnonRecord) {
4145 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4146 AnonRecord);
4147}
4148
4149// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4150// disambiguate entities defined in different scopes.
4151// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4152// compatibility.
4153// We will pick our mangling number depending on which version of MSVC is being
4154// targeted.
4155static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4156 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4157 ? S->getMSCurManglingNumber()
4158 : S->getMSLastManglingNumber();
4159}
4160
4161void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4162 if (!Context.getLangOpts().CPlusPlus)
4163 return;
4164
4165 if (isa<CXXRecordDecl>(Tag->getParent())) {
4166 // If this tag is the direct child of a class, number it if
4167 // it is anonymous.
4168 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4169 return;
4170 MangleNumberingContext &MCtx =
4171 Context.getManglingNumberContext(Tag->getParent());
4172 Context.setManglingNumber(
4173 Tag, MCtx.getManglingNumber(
4174 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4175 return;
4176 }
4177
4178 // If this tag isn't a direct child of a class, number it if it is local.
4179 Decl *ManglingContextDecl;
4180 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4181 Tag->getDeclContext(), ManglingContextDecl)) {
4182 Context.setManglingNumber(
4183 Tag, MCtx->getManglingNumber(
4184 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4185 }
4186}
4187
4188void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4189 TypedefNameDecl *NewTD) {
4190 if (TagFromDeclSpec->isInvalidDecl())
4191 return;
4192
4193 // Do nothing if the tag already has a name for linkage purposes.
4194 if (TagFromDeclSpec->hasNameForLinkage())
4195 return;
4196
4197 // A well-formed anonymous tag must always be a TUK_Definition.
4198 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4199
4200 // The type must match the tag exactly; no qualifiers allowed.
4201 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4202 Context.getTagDeclType(TagFromDeclSpec))) {
4203 if (getLangOpts().CPlusPlus)
4204 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4205 return;
4206 }
4207
4208 // If we've already computed linkage for the anonymous tag, then
4209 // adding a typedef name for the anonymous decl can change that
4210 // linkage, which might be a serious problem. Diagnose this as
4211 // unsupported and ignore the typedef name. TODO: we should
4212 // pursue this as a language defect and establish a formal rule
4213 // for how to handle it.
4214 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4215 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4216
4217 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4218 tagLoc = getLocForEndOfToken(tagLoc);
4219
4220 llvm::SmallString<40> textToInsert;
4221 textToInsert += ' ';
4222 textToInsert += NewTD->getIdentifier()->getName();
4223 Diag(tagLoc, diag::note_typedef_changes_linkage)
4224 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4225 return;
4226 }
4227
4228 // Otherwise, set this is the anon-decl typedef for the tag.
4229 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4230}
4231
4232static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4233 switch (T) {
4234 case DeclSpec::TST_class:
4235 return 0;
4236 case DeclSpec::TST_struct:
4237 return 1;
4238 case DeclSpec::TST_interface:
4239 return 2;
4240 case DeclSpec::TST_union:
4241 return 3;
4242 case DeclSpec::TST_enum:
4243 return 4;
4244 default:
4245 llvm_unreachable("unexpected type specifier");
4246 }
4247}
4248
4249/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4250/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4251/// parameters to cope with template friend declarations.
4252Decl *
4253Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4254 MultiTemplateParamsArg TemplateParams,
4255 bool IsExplicitInstantiation,
4256 RecordDecl *&AnonRecord) {
4257 Decl *TagD = nullptr;
4258 TagDecl *Tag = nullptr;
4259 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4260 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4261 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4262 DS.getTypeSpecType() == DeclSpec::TST_union ||
4263 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4264 TagD = DS.getRepAsDecl();
4265
4266 if (!TagD) // We probably had an error
4267 return nullptr;
4268
4269 // Note that the above type specs guarantee that the
4270 // type rep is a Decl, whereas in many of the others
4271 // it's a Type.
4272 if (isa<TagDecl>(TagD))
4273 Tag = cast<TagDecl>(TagD);
4274 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4275 Tag = CTD->getTemplatedDecl();
4276 }
4277
4278 if (Tag) {
4279 handleTagNumbering(Tag, S);
4280 Tag->setFreeStanding();
4281 if (Tag->isInvalidDecl())
4282 return Tag;
4283 }
4284
4285 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4286 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4287 // or incomplete types shall not be restrict-qualified."
4288 if (TypeQuals & DeclSpec::TQ_restrict)
4289 Diag(DS.getRestrictSpecLoc(),
4290 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4291 << DS.getSourceRange();
4292 }
4293
4294 if (DS.isInlineSpecified())
4295 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4296 << getLangOpts().CPlusPlus17;
4297
4298 if (DS.isConstexprSpecified()) {
4299 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4300 // and definitions of functions and variables.
4301 if (Tag)
4302 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4303 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4304 else
4305 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4306 // Don't emit warnings after this error.
4307 return TagD;
4308 }
4309
4310 DiagnoseFunctionSpecifiers(DS);
4311
4312 if (DS.isFriendSpecified()) {
4313 // If we're dealing with a decl but not a TagDecl, assume that
4314 // whatever routines created it handled the friendship aspect.
4315 if (TagD && !Tag)
4316 return nullptr;
4317 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4318 }
4319
4320 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4321 bool IsExplicitSpecialization =
4322 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4323 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4324 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4325 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4326 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4327 // nested-name-specifier unless it is an explicit instantiation
4328 // or an explicit specialization.
4329 //
4330 // FIXME: We allow class template partial specializations here too, per the
4331 // obvious intent of DR1819.
4332 //
4333 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4334 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4335 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4336 return nullptr;
4337 }
4338
4339 // Track whether this decl-specifier declares anything.
4340 bool DeclaresAnything = true;
4341
4342 // Handle anonymous struct definitions.
4343 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4344 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4345 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4346 if (getLangOpts().CPlusPlus ||
4347 Record->getDeclContext()->isRecord()) {
4348 // If CurContext is a DeclContext that can contain statements,
4349 // RecursiveASTVisitor won't visit the decls that
4350 // BuildAnonymousStructOrUnion() will put into CurContext.
4351 // Also store them here so that they can be part of the
4352 // DeclStmt that gets created in this case.
4353 // FIXME: Also return the IndirectFieldDecls created by
4354 // BuildAnonymousStructOr union, for the same reason?
4355 if (CurContext->isFunctionOrMethod())
4356 AnonRecord = Record;
4357 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4358 Context.getPrintingPolicy());
4359 }
4360
4361 DeclaresAnything = false;
4362 }
4363 }
4364
4365 // C11 6.7.2.1p2:
4366 // A struct-declaration that does not declare an anonymous structure or
4367 // anonymous union shall contain a struct-declarator-list.
4368 //
4369 // This rule also existed in C89 and C99; the grammar for struct-declaration
4370 // did not permit a struct-declaration without a struct-declarator-list.
4371 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4372 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4373 // Check for Microsoft C extension: anonymous struct/union member.
4374 // Handle 2 kinds of anonymous struct/union:
4375 // struct STRUCT;
4376 // union UNION;
4377 // and
4378 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4379 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4380 if ((Tag && Tag->getDeclName()) ||
4381 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4382 RecordDecl *Record = nullptr;
4383 if (Tag)
4384 Record = dyn_cast<RecordDecl>(Tag);
4385 else if (const RecordType *RT =
4386 DS.getRepAsType().get()->getAsStructureType())
4387 Record = RT->getDecl();
4388 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4389 Record = UT->getDecl();
4390
4391 if (Record && getLangOpts().MicrosoftExt) {
4392 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4393 << Record->isUnion() << DS.getSourceRange();
4394 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4395 }
4396
4397 DeclaresAnything = false;
4398 }
4399 }
4400
4401 // Skip all the checks below if we have a type error.
4402 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4403 (TagD && TagD->isInvalidDecl()))
4404 return TagD;
4405
4406 if (getLangOpts().CPlusPlus &&
4407 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4408 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4409 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4410 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4411 DeclaresAnything = false;
4412
4413 if (!DS.isMissingDeclaratorOk()) {
4414 // Customize diagnostic for a typedef missing a name.
4415 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4416 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4417 << DS.getSourceRange();
4418 else
4419 DeclaresAnything = false;
4420 }
4421
4422 if (DS.isModulePrivateSpecified() &&
4423 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4424 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4425 << Tag->getTagKind()
4426 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4427
4428 ActOnDocumentableDecl(TagD);
4429
4430 // C 6.7/2:
4431 // A declaration [...] shall declare at least a declarator [...], a tag,
4432 // or the members of an enumeration.
4433 // C++ [dcl.dcl]p3:
4434 // [If there are no declarators], and except for the declaration of an
4435 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4436 // names into the program, or shall redeclare a name introduced by a
4437 // previous declaration.
4438 if (!DeclaresAnything) {
4439 // In C, we allow this as a (popular) extension / bug. Don't bother
4440 // producing further diagnostics for redundant qualifiers after this.
4441 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4442 return TagD;
4443 }
4444
4445 // C++ [dcl.stc]p1:
4446 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4447 // init-declarator-list of the declaration shall not be empty.
4448 // C++ [dcl.fct.spec]p1:
4449 // If a cv-qualifier appears in a decl-specifier-seq, the
4450 // init-declarator-list of the declaration shall not be empty.
4451 //
4452 // Spurious qualifiers here appear to be valid in C.
4453 unsigned DiagID = diag::warn_standalone_specifier;
4454 if (getLangOpts().CPlusPlus)
4455 DiagID = diag::ext_standalone_specifier;
4456
4457 // Note that a linkage-specification sets a storage class, but
4458 // 'extern "C" struct foo;' is actually valid and not theoretically
4459 // useless.
4460 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4461 if (SCS == DeclSpec::SCS_mutable)
4462 // Since mutable is not a viable storage class specifier in C, there is
4463 // no reason to treat it as an extension. Instead, diagnose as an error.
4464 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4465 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4466 Diag(DS.getStorageClassSpecLoc(), DiagID)
4467 << DeclSpec::getSpecifierName(SCS);
4468 }
4469
4470 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4471 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4472 << DeclSpec::getSpecifierName(TSCS);
4473 if (DS.getTypeQualifiers()) {
4474 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4475 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4476 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4477 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4478 // Restrict is covered above.
4479 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4480 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4481 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4482 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4483 }
4484
4485 // Warn about ignored type attributes, for example:
4486 // __attribute__((aligned)) struct A;
4487 // Attributes should be placed after tag to apply to type declaration.
4488 if (!DS.getAttributes().empty()) {
4489 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4490 if (TypeSpecType == DeclSpec::TST_class ||
4491 TypeSpecType == DeclSpec::TST_struct ||
4492 TypeSpecType == DeclSpec::TST_interface ||
4493 TypeSpecType == DeclSpec::TST_union ||
4494 TypeSpecType == DeclSpec::TST_enum) {
4495 for (const ParsedAttr &AL : DS.getAttributes())
4496 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4497 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4498 }
4499 }
4500
4501 return TagD;
4502}
4503
4504/// We are trying to inject an anonymous member into the given scope;
4505/// check if there's an existing declaration that can't be overloaded.
4506///
4507/// \return true if this is a forbidden redeclaration
4508static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4509 Scope *S,
4510 DeclContext *Owner,
4511 DeclarationName Name,
4512 SourceLocation NameLoc,
4513 bool IsUnion) {
4514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4515 Sema::ForVisibleRedeclaration);
4516 if (!SemaRef.LookupName(R, S)) return false;
4517
4518 // Pick a representative declaration.
4519 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4520 assert(PrevDecl && "Expected a non-null Decl");
4521
4522 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4523 return false;
4524
4525 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4526 << IsUnion << Name;
4527 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4528
4529 return true;
4530}
4531
4532/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4533/// anonymous struct or union AnonRecord into the owning context Owner
4534/// and scope S. This routine will be invoked just after we realize
4535/// that an unnamed union or struct is actually an anonymous union or
4536/// struct, e.g.,
4537///
4538/// @code
4539/// union {
4540/// int i;
4541/// float f;
4542/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4543/// // f into the surrounding scope.x
4544/// @endcode
4545///
4546/// This routine is recursive, injecting the names of nested anonymous
4547/// structs/unions into the owning context and scope as well.
4548static bool
4549InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4550 RecordDecl *AnonRecord, AccessSpecifier AS,
4551 SmallVectorImpl<NamedDecl *> &Chaining) {
4552 bool Invalid = false;
4553
4554 // Look every FieldDecl and IndirectFieldDecl with a name.
4555 for (auto *D : AnonRecord->decls()) {
4556 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4557 cast<NamedDecl>(D)->getDeclName()) {
4558 ValueDecl *VD = cast<ValueDecl>(D);
4559 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4560 VD->getLocation(),
4561 AnonRecord->isUnion())) {
4562 // C++ [class.union]p2:
4563 // The names of the members of an anonymous union shall be
4564 // distinct from the names of any other entity in the
4565 // scope in which the anonymous union is declared.
4566 Invalid = true;
4567 } else {
4568 // C++ [class.union]p2:
4569 // For the purpose of name lookup, after the anonymous union
4570 // definition, the members of the anonymous union are
4571 // considered to have been defined in the scope in which the
4572 // anonymous union is declared.
4573 unsigned OldChainingSize = Chaining.size();
4574 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4575 Chaining.append(IF->chain_begin(), IF->chain_end());
4576 else
4577 Chaining.push_back(VD);
4578
4579 assert(Chaining.size() >= 2);
4580 NamedDecl **NamedChain =
4581 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4582 for (unsigned i = 0; i < Chaining.size(); i++)
4583 NamedChain[i] = Chaining[i];
4584
4585 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4586 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4587 VD->getType(), {NamedChain, Chaining.size()});
4588
4589 for (const auto *Attr : VD->attrs())
4590 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4591
4592 IndirectField->setAccess(AS);
4593 IndirectField->setImplicit();
4594 SemaRef.PushOnScopeChains(IndirectField, S);
4595
4596 // That includes picking up the appropriate access specifier.
4597 if (AS != AS_none) IndirectField->setAccess(AS);
4598
4599 Chaining.resize(OldChainingSize);
4600 }
4601 }
4602 }
4603
4604 return Invalid;
4605}
4606
4607/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4608/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4609/// illegal input values are mapped to SC_None.
4610static StorageClass
4611StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4612 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4613 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4614 "Parser allowed 'typedef' as storage class VarDecl.");
4615 switch (StorageClassSpec) {
4616 case DeclSpec::SCS_unspecified: return SC_None;
4617 case DeclSpec::SCS_extern:
4618 if (DS.isExternInLinkageSpec())
4619 return SC_None;
4620 return SC_Extern;
4621 case DeclSpec::SCS_static: return SC_Static;
4622 case DeclSpec::SCS_auto: return SC_Auto;
4623 case DeclSpec::SCS_register: return SC_Register;
4624 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4625 // Illegal SCSs map to None: error reporting is up to the caller.
4626 case DeclSpec::SCS_mutable: // Fall through.
4627 case DeclSpec::SCS_typedef: return SC_None;
4628 }
4629 llvm_unreachable("unknown storage class specifier");
4630}
4631
4632static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4633 assert(Record->hasInClassInitializer());
4634
4635 for (const auto *I : Record->decls()) {
4636 const auto *FD = dyn_cast<FieldDecl>(I);
4637 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4638 FD = IFD->getAnonField();
4639 if (FD && FD->hasInClassInitializer())
4640 return FD->getLocation();
4641 }
4642
4643 llvm_unreachable("couldn't find in-class initializer");
4644}
4645
4646static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4647 SourceLocation DefaultInitLoc) {
4648 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4649 return;
4650
4651 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4652 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4653}
4654
4655static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4656 CXXRecordDecl *AnonUnion) {
4657 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4658 return;
4659
4660 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4661}
4662
4663/// BuildAnonymousStructOrUnion - Handle the declaration of an
4664/// anonymous structure or union. Anonymous unions are a C++ feature
4665/// (C++ [class.union]) and a C11 feature; anonymous structures
4666/// are a C11 feature and GNU C++ extension.
4667Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4668 AccessSpecifier AS,
4669 RecordDecl *Record,
4670 const PrintingPolicy &Policy) {
4671 DeclContext *Owner = Record->getDeclContext();
4672
4673 // Diagnose whether this anonymous struct/union is an extension.
4674 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4675 Diag(Record->getLocation(), diag::ext_anonymous_union);
4676 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4677 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4678 else if (!Record->isUnion() && !getLangOpts().C11)
4679 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4680
4681 // C and C++ require different kinds of checks for anonymous
4682 // structs/unions.
4683 bool Invalid = false;
4684 if (getLangOpts().CPlusPlus) {
4685 const char *PrevSpec = nullptr;
4686 unsigned DiagID;
4687 if (Record->isUnion()) {
4688 // C++ [class.union]p6:
4689 // C++17 [class.union.anon]p2:
4690 // Anonymous unions declared in a named namespace or in the
4691 // global namespace shall be declared static.
4692 DeclContext *OwnerScope = Owner->getRedeclContext();
4693 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4694 (OwnerScope->isTranslationUnit() ||
4695 (OwnerScope->isNamespace() &&
4696 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4697 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4698 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4699
4700 // Recover by adding 'static'.
4701 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4702 PrevSpec, DiagID, Policy);
4703 }
4704 // C++ [class.union]p6:
4705 // A storage class is not allowed in a declaration of an
4706 // anonymous union in a class scope.
4707 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4708 isa<RecordDecl>(Owner)) {
4709 Diag(DS.getStorageClassSpecLoc(),
4710 diag::err_anonymous_union_with_storage_spec)
4711 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4712
4713 // Recover by removing the storage specifier.
4714 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4715 SourceLocation(),
4716 PrevSpec, DiagID, Context.getPrintingPolicy());
4717 }
4718 }
4719
4720 // Ignore const/volatile/restrict qualifiers.
4721 if (DS.getTypeQualifiers()) {
4722 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4723 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4724 << Record->isUnion() << "const"
4725 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4726 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4727 Diag(DS.getVolatileSpecLoc(),
4728 diag::ext_anonymous_struct_union_qualified)
4729 << Record->isUnion() << "volatile"
4730 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4731 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4732 Diag(DS.getRestrictSpecLoc(),
4733 diag::ext_anonymous_struct_union_qualified)
4734 << Record->isUnion() << "restrict"
4735 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4736 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4737 Diag(DS.getAtomicSpecLoc(),
4738 diag::ext_anonymous_struct_union_qualified)
4739 << Record->isUnion() << "_Atomic"
4740 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4741 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4742 Diag(DS.getUnalignedSpecLoc(),
4743 diag::ext_anonymous_struct_union_qualified)
4744 << Record->isUnion() << "__unaligned"
4745 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4746
4747 DS.ClearTypeQualifiers();
4748 }
4749
4750 // C++ [class.union]p2:
4751 // The member-specification of an anonymous union shall only
4752 // define non-static data members. [Note: nested types and
4753 // functions cannot be declared within an anonymous union. ]
4754 for (auto *Mem : Record->decls()) {
4755 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4756 // C++ [class.union]p3:
4757 // An anonymous union shall not have private or protected
4758 // members (clause 11).
4759 assert(FD->getAccess() != AS_none);
4760 if (FD->getAccess() != AS_public) {
4761 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4762 << Record->isUnion() << (FD->getAccess() == AS_protected);
4763 Invalid = true;
4764 }
4765
4766 // C++ [class.union]p1
4767 // An object of a class with a non-trivial constructor, a non-trivial
4768 // copy constructor, a non-trivial destructor, or a non-trivial copy
4769 // assignment operator cannot be a member of a union, nor can an
4770 // array of such objects.
4771 if (CheckNontrivialField(FD))
4772 Invalid = true;
4773 } else if (Mem->isImplicit()) {
4774 // Any implicit members are fine.
4775 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4776 // This is a type that showed up in an
4777 // elaborated-type-specifier inside the anonymous struct or
4778 // union, but which actually declares a type outside of the
4779 // anonymous struct or union. It's okay.
4780 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4781 if (!MemRecord->isAnonymousStructOrUnion() &&
4782 MemRecord->getDeclName()) {
4783 // Visual C++ allows type definition in anonymous struct or union.
4784 if (getLangOpts().MicrosoftExt)
4785 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4786 << Record->isUnion();
4787 else {
4788 // This is a nested type declaration.
4789 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4790 << Record->isUnion();
4791 Invalid = true;
4792 }
4793 } else {
4794 // This is an anonymous type definition within another anonymous type.
4795 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4796 // not part of standard C++.
4797 Diag(MemRecord->getLocation(),
4798 diag::ext_anonymous_record_with_anonymous_type)
4799 << Record->isUnion();
4800 }
4801 } else if (isa<AccessSpecDecl>(Mem)) {
4802 // Any access specifier is fine.
4803 } else if (isa<StaticAssertDecl>(Mem)) {
4804 // In C++1z, static_assert declarations are also fine.
4805 } else {
4806 // We have something that isn't a non-static data
4807 // member. Complain about it.
4808 unsigned DK = diag::err_anonymous_record_bad_member;
4809 if (isa<TypeDecl>(Mem))
4810 DK = diag::err_anonymous_record_with_type;
4811 else if (isa<FunctionDecl>(Mem))
4812 DK = diag::err_anonymous_record_with_function;
4813 else if (isa<VarDecl>(Mem))
4814 DK = diag::err_anonymous_record_with_static;
4815
4816 // Visual C++ allows type definition in anonymous struct or union.
4817 if (getLangOpts().MicrosoftExt &&
4818 DK == diag::err_anonymous_record_with_type)
4819 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4820 << Record->isUnion();
4821 else {
4822 Diag(Mem->getLocation(), DK) << Record->isUnion();
4823 Invalid = true;
4824 }
4825 }
4826 }
4827
4828 // C++11 [class.union]p8 (DR1460):
4829 // At most one variant member of a union may have a
4830 // brace-or-equal-initializer.
4831 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4832 Owner->isRecord())
4833 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4834 cast<CXXRecordDecl>(Record));
4835 }
4836
4837 if (!Record->isUnion() && !Owner->isRecord()) {
4838 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4839 << getLangOpts().CPlusPlus;
4840 Invalid = true;
4841 }
4842
4843 // C++ [dcl.dcl]p3:
4844 // [If there are no declarators], and except for the declaration of an
4845 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4846 // names into the program
4847 // C++ [class.mem]p2:
4848 // each such member-declaration shall either declare at least one member
4849 // name of the class or declare at least one unnamed bit-field
4850 //
4851 // For C this is an error even for a named struct, and is diagnosed elsewhere.
4852 if (getLangOpts().CPlusPlus && Record->field_empty())
4853 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4854
4855 // Mock up a declarator.
4856 Declarator Dc(DS, DeclaratorContext::MemberContext);
4857 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4858 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4859
4860 // Create a declaration for this anonymous struct/union.
4861 NamedDecl *Anon = nullptr;
4862 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4863 Anon = FieldDecl::Create(
4864 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4865 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4866 /*BitWidth=*/nullptr, /*Mutable=*/false,
4867 /*InitStyle=*/ICIS_NoInit);
4868 Anon->setAccess(AS);
4869 if (getLangOpts().CPlusPlus)
4870 FieldCollector->Add(cast<FieldDecl>(Anon));
4871 } else {
4872 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4873 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4874 if (SCSpec == DeclSpec::SCS_mutable) {
4875 // mutable can only appear on non-static class members, so it's always
4876 // an error here
4877 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4878 Invalid = true;
4879 SC = SC_None;
4880 }
4881
4882 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4883 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4884 Context.getTypeDeclType(Record), TInfo, SC);
4885
4886 // Default-initialize the implicit variable. This initialization will be
4887 // trivial in almost all cases, except if a union member has an in-class
4888 // initializer:
4889 // union { int n = 0; };
4890 ActOnUninitializedDecl(Anon);
4891 }
4892 Anon->setImplicit();
4893
4894 // Mark this as an anonymous struct/union type.
4895 Record->setAnonymousStructOrUnion(true);
4896
4897 // Add the anonymous struct/union object to the current
4898 // context. We'll be referencing this object when we refer to one of
4899 // its members.
4900 Owner->addDecl(Anon);
4901
4902 // Inject the members of the anonymous struct/union into the owning
4903 // context and into the identifier resolver chain for name lookup
4904 // purposes.
4905 SmallVector<NamedDecl*, 2> Chain;
4906 Chain.push_back(Anon);
4907
4908 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4909 Invalid = true;
4910
4911 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4912 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4913 Decl *ManglingContextDecl;
4914 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4915 NewVD->getDeclContext(), ManglingContextDecl)) {
4916 Context.setManglingNumber(
4917 NewVD, MCtx->getManglingNumber(
4918 NewVD, getMSManglingNumber(getLangOpts(), S)));
4919 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4920 }
4921 }
4922 }
4923
4924 if (Invalid)
4925 Anon->setInvalidDecl();
4926
4927 return Anon;
4928}
4929
4930/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4931/// Microsoft C anonymous structure.
4932/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4933/// Example:
4934///
4935/// struct A { int a; };
4936/// struct B { struct A; int b; };
4937///
4938/// void foo() {
4939/// B var;
4940/// var.a = 3;
4941/// }
4942///
4943Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4944 RecordDecl *Record) {
4945 assert(Record && "expected a record!");
4946
4947 // Mock up a declarator.
4948 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4949 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4950 assert(TInfo && "couldn't build declarator info for anonymous struct");
4951
4952 auto *ParentDecl = cast<RecordDecl>(CurContext);
4953 QualType RecTy = Context.getTypeDeclType(Record);
4954
4955 // Create a declaration for this anonymous struct.
4956 NamedDecl *Anon =
4957 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4958 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4959 /*BitWidth=*/nullptr, /*Mutable=*/false,
4960 /*InitStyle=*/ICIS_NoInit);
4961 Anon->setImplicit();
4962
4963 // Add the anonymous struct object to the current context.
4964 CurContext->addDecl(Anon);
4965
4966 // Inject the members of the anonymous struct into the current
4967 // context and into the identifier resolver chain for name lookup
4968 // purposes.
4969 SmallVector<NamedDecl*, 2> Chain;
4970 Chain.push_back(Anon);
4971
4972 RecordDecl *RecordDef = Record->getDefinition();
4973 if (RequireCompleteType(Anon->getLocation(), RecTy,
4974 diag::err_field_incomplete) ||
4975 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4976 AS_none, Chain)) {
4977 Anon->setInvalidDecl();
4978 ParentDecl->setInvalidDecl();
4979 }
4980
4981 return Anon;
4982}
4983
4984/// GetNameForDeclarator - Determine the full declaration name for the
4985/// given Declarator.
4986DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4987 return GetNameFromUnqualifiedId(D.getName());
4988}
4989
4990/// Retrieves the declaration name from a parsed unqualified-id.
4991DeclarationNameInfo
4992Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4993 DeclarationNameInfo NameInfo;
4994 NameInfo.setLoc(Name.StartLocation);
4995
4996 switch (Name.getKind()) {
4997
4998 case UnqualifiedIdKind::IK_ImplicitSelfParam:
4999 case UnqualifiedIdKind::IK_Identifier:
5000 NameInfo.setName(Name.Identifier);
5001 return NameInfo;
5002
5003 case UnqualifiedIdKind::IK_DeductionGuideName: {
5004 // C++ [temp.deduct.guide]p3:
5005 // The simple-template-id shall name a class template specialization.
5006 // The template-name shall be the same identifier as the template-name
5007 // of the simple-template-id.
5008 // These together intend to imply that the template-name shall name a
5009 // class template.
5010 // FIXME: template<typename T> struct X {};
5011 // template<typename T> using Y = X<T>;
5012 // Y(int) -> Y<int>;
5013 // satisfies these rules but does not name a class template.
5014 TemplateName TN = Name.TemplateName.get().get();
5015 auto *Template = TN.getAsTemplateDecl();
5016 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5017 Diag(Name.StartLocation,
5018 diag::err_deduction_guide_name_not_class_template)
5019 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5020 if (Template)
5021 Diag(Template->getLocation(), diag::note_template_decl_here);
5022 return DeclarationNameInfo();
5023 }
5024
5025 NameInfo.setName(
5026 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5027 return NameInfo;
5028 }
5029
5030 case UnqualifiedIdKind::IK_OperatorFunctionId:
5031 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5032 Name.OperatorFunctionId.Operator));
5033 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5034 = Name.OperatorFunctionId.SymbolLocations[0];
5035 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5036 = Name.EndLocation.getRawEncoding();
5037 return NameInfo;
5038
5039 case UnqualifiedIdKind::IK_LiteralOperatorId:
5040 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5041 Name.Identifier));
5042 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5043 return NameInfo;
5044
5045 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5046 TypeSourceInfo *TInfo;
5047 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5048 if (Ty.isNull())
5049 return DeclarationNameInfo();
5050 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5051 Context.getCanonicalType(Ty)));
5052 NameInfo.setNamedTypeInfo(TInfo);
5053 return NameInfo;
5054 }
5055
5056 case UnqualifiedIdKind::IK_ConstructorName: {
5057 TypeSourceInfo *TInfo;
5058 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5059 if (Ty.isNull())
5060 return DeclarationNameInfo();
5061 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5062 Context.getCanonicalType(Ty)));
5063 NameInfo.setNamedTypeInfo(TInfo);
5064 return NameInfo;
5065 }
5066
5067 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5068 // In well-formed code, we can only have a constructor
5069 // template-id that refers to the current context, so go there
5070 // to find the actual type being constructed.
5071 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5072 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5073 return DeclarationNameInfo();
5074
5075 // Determine the type of the class being constructed.
5076 QualType CurClassType = Context.getTypeDeclType(CurClass);
5077
5078 // FIXME: Check two things: that the template-id names the same type as
5079 // CurClassType, and that the template-id does not occur when the name
5080 // was qualified.
5081
5082 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5083 Context.getCanonicalType(CurClassType)));
5084 // FIXME: should we retrieve TypeSourceInfo?
5085 NameInfo.setNamedTypeInfo(nullptr);
5086 return NameInfo;
5087 }
5088
5089 case UnqualifiedIdKind::IK_DestructorName: {
5090 TypeSourceInfo *TInfo;
5091 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5092 if (Ty.isNull())
5093 return DeclarationNameInfo();
5094 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5095 Context.getCanonicalType(Ty)));
5096 NameInfo.setNamedTypeInfo(TInfo);
5097 return NameInfo;
5098 }
5099
5100 case UnqualifiedIdKind::IK_TemplateId: {
5101 TemplateName TName = Name.TemplateId->Template.get();
5102 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5103 return Context.getNameForTemplate(TName, TNameLoc);
5104 }
5105
5106 } // switch (Name.getKind())
5107
5108 llvm_unreachable("Unknown name kind");
5109}
5110
5111static QualType getCoreType(QualType Ty) {
5112 do {
5113 if (Ty->isPointerType() || Ty->isReferenceType())
5114 Ty = Ty->getPointeeType();
5115 else if (Ty->isArrayType())
5116 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5117 else
5118 return Ty.withoutLocalFastQualifiers();
5119 } while (true);
5120}
5121
5122/// hasSimilarParameters - Determine whether the C++ functions Declaration
5123/// and Definition have "nearly" matching parameters. This heuristic is
5124/// used to improve diagnostics in the case where an out-of-line function
5125/// definition doesn't match any declaration within the class or namespace.
5126/// Also sets Params to the list of indices to the parameters that differ
5127/// between the declaration and the definition. If hasSimilarParameters
5128/// returns true and Params is empty, then all of the parameters match.
5129static bool hasSimilarParameters(ASTContext &Context,
5130 FunctionDecl *Declaration,
5131 FunctionDecl *Definition,
5132 SmallVectorImpl<unsigned> &Params) {
5133 Params.clear();
5134 if (Declaration->param_size() != Definition->param_size())
5135 return false;
5136 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5137 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5138 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5139
5140 // The parameter types are identical
5141 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5142 continue;
5143
5144 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5145 QualType DefParamBaseTy = getCoreType(DefParamTy);
5146 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5147 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5148
5149 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5150 (DeclTyName && DeclTyName == DefTyName))
5151 Params.push_back(Idx);
5152 else // The two parameters aren't even close
5153 return false;
5154 }
5155
5156 return true;
5157}
5158
5159/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5160/// declarator needs to be rebuilt in the current instantiation.
5161/// Any bits of declarator which appear before the name are valid for
5162/// consideration here. That's specifically the type in the decl spec
5163/// and the base type in any member-pointer chunks.
5164static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5165 DeclarationName Name) {
5166 // The types we specifically need to rebuild are:
5167 // - typenames, typeofs, and decltypes
5168 // - types which will become injected class names
5169 // Of course, we also need to rebuild any type referencing such a
5170 // type. It's safest to just say "dependent", but we call out a
5171 // few cases here.
5172
5173 DeclSpec &DS = D.getMutableDeclSpec();
5174 switch (DS.getTypeSpecType()) {
5175 case DeclSpec::TST_typename:
5176 case DeclSpec::TST_typeofType:
5177 case DeclSpec::TST_underlyingType:
5178 case DeclSpec::TST_atomic: {
5179 // Grab the type from the parser.
5180 TypeSourceInfo *TSI = nullptr;
5181 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5182 if (T.isNull() || !T->isDependentType()) break;
5183
5184 // Make sure there's a type source info. This isn't really much
5185 // of a waste; most dependent types should have type source info
5186 // attached already.
5187 if (!TSI)
5188 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5189
5190 // Rebuild the type in the current instantiation.
5191 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5192 if (!TSI) return true;
5193
5194 // Store the new type back in the decl spec.
5195 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5196 DS.UpdateTypeRep(LocType);
5197 break;
5198 }
5199
5200 case DeclSpec::TST_decltype:
5201 case DeclSpec::TST_typeofExpr: {
5202 Expr *E = DS.getRepAsExpr();
5203 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5204 if (Result.isInvalid()) return true;
5205 DS.UpdateExprRep(Result.get());
5206 break;
5207 }
5208
5209 default:
5210 // Nothing to do for these decl specs.
5211 break;
5212 }
5213
5214 // It doesn't matter what order we do this in.
5215 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5216 DeclaratorChunk &Chunk = D.getTypeObject(I);
5217
5218 // The only type information in the declarator which can come
5219 // before the declaration name is the base type of a member
5220 // pointer.
5221 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5222 continue;
5223
5224 // Rebuild the scope specifier in-place.
5225 CXXScopeSpec &SS = Chunk.Mem.Scope();
5226 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5227 return true;
5228 }
5229
5230 return false;
5231}
5232
5233Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5234 D.setFunctionDefinitionKind(FDK_Declaration);
5235 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5236
5237 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5238 Dcl && Dcl->getDeclContext()->isFileContext())
5239 Dcl->setTopLevelDeclInObjCContainer();
5240
5241 if (getLangOpts().OpenCL)
5242 setCurrentOpenCLExtensionForDecl(Dcl);
5243
5244 return Dcl;
5245}
5246
5247/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5248/// If T is the name of a class, then each of the following shall have a
5249/// name different from T:
5250/// - every static data member of class T;
5251/// - every member function of class T
5252/// - every member of class T that is itself a type;
5253/// \returns true if the declaration name violates these rules.
5254bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5255 DeclarationNameInfo NameInfo) {
5256 DeclarationName Name = NameInfo.getName();
5257
5258 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5259 while (Record && Record->isAnonymousStructOrUnion())
5260 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5261 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5262 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5263 return true;
5264 }
5265
5266 return false;
5267}
5268
5269/// Diagnose a declaration whose declarator-id has the given
5270/// nested-name-specifier.
5271///
5272/// \param SS The nested-name-specifier of the declarator-id.
5273///
5274/// \param DC The declaration context to which the nested-name-specifier
5275/// resolves.
5276///
5277/// \param Name The name of the entity being declared.
5278///
5279/// \param Loc The location of the name of the entity being declared.
5280///
5281/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5282/// we're declaring an explicit / partial specialization / instantiation.
5283///
5284/// \returns true if we cannot safely recover from this error, false otherwise.
5285bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5286 DeclarationName Name,
5287 SourceLocation Loc, bool IsTemplateId) {
5288 DeclContext *Cur = CurContext;
5289 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5290 Cur = Cur->getParent();
5291
5292 // If the user provided a superfluous scope specifier that refers back to the
5293 // class in which the entity is already declared, diagnose and ignore it.
5294 //
5295 // class X {
5296 // void X::f();
5297 // };
5298 //
5299 // Note, it was once ill-formed to give redundant qualification in all
5300 // contexts, but that rule was removed by DR482.
5301 if (Cur->Equals(DC)) {
5302 if (Cur->isRecord()) {
5303 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5304 : diag::err_member_extra_qualification)
5305 << Name << FixItHint::CreateRemoval(SS.getRange());
5306 SS.clear();
5307 } else {
5308 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5309 }
5310 return false;
5311 }
5312
5313 // Check whether the qualifying scope encloses the scope of the original
5314 // declaration. For a template-id, we perform the checks in
5315 // CheckTemplateSpecializationScope.
5316 if (!Cur->Encloses(DC) && !IsTemplateId) {
5317 if (Cur->isRecord())
5318 Diag(Loc, diag::err_member_qualification)
5319 << Name << SS.getRange();
5320 else if (isa<TranslationUnitDecl>(DC))
5321 Diag(Loc, diag::err_invalid_declarator_global_scope)
5322 << Name << SS.getRange();
5323 else if (isa<FunctionDecl>(Cur))
5324 Diag(Loc, diag::err_invalid_declarator_in_function)
5325 << Name << SS.getRange();
5326 else if (isa<BlockDecl>(Cur))
5327 Diag(Loc, diag::err_invalid_declarator_in_block)
5328 << Name << SS.getRange();
5329 else
5330 Diag(Loc, diag::err_invalid_declarator_scope)
5331 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5332
5333 return true;
5334 }
5335
5336 if (Cur->isRecord()) {
5337 // Cannot qualify members within a class.
5338 Diag(Loc, diag::err_member_qualification)
5339 << Name << SS.getRange();
5340 SS.clear();
5341
5342 // C++ constructors and destructors with incorrect scopes can break
5343 // our AST invariants by having the wrong underlying types. If
5344 // that's the case, then drop this declaration entirely.
5345 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5346 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5347 !Context.hasSameType(Name.getCXXNameType(),
5348 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5349 return true;
5350
5351 return false;
5352 }
5353
5354 // C++11 [dcl.meaning]p1:
5355 // [...] "The nested-name-specifier of the qualified declarator-id shall
5356 // not begin with a decltype-specifer"
5357 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5358 while (SpecLoc.getPrefix())
5359 SpecLoc = SpecLoc.getPrefix();
5360 if (dyn_cast_or_null<DecltypeType>(
5361 SpecLoc.getNestedNameSpecifier()->getAsType()))
5362 Diag(Loc, diag::err_decltype_in_declarator)
5363 << SpecLoc.getTypeLoc().getSourceRange();
5364
5365 return false;
5366}
5367
5368NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5369 MultiTemplateParamsArg TemplateParamLists) {
5370 // TODO: consider using NameInfo for diagnostic.
5371 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5372 DeclarationName Name = NameInfo.getName();
5373
5374 // All of these full declarators require an identifier. If it doesn't have
5375 // one, the ParsedFreeStandingDeclSpec action should be used.
5376 if (D.isDecompositionDeclarator()) {
5377 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5378 } else if (!Name) {
5379 if (!D.isInvalidType()) // Reject this if we think it is valid.
5380 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5381 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5382 return nullptr;
5383 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5384 return nullptr;
5385
5386 // The scope passed in may not be a decl scope. Zip up the scope tree until
5387 // we find one that is.
5388 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5389 (S->getFlags() & Scope::TemplateParamScope) != 0)
5390 S = S->getParent();
5391
5392 DeclContext *DC = CurContext;
5393 if (D.getCXXScopeSpec().isInvalid())
5394 D.setInvalidType();
5395 else if (D.getCXXScopeSpec().isSet()) {
5396 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5397 UPPC_DeclarationQualifier))
5398 return nullptr;
5399
5400 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5401 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5402 if (!DC || isa<EnumDecl>(DC)) {
5403 // If we could not compute the declaration context, it's because the
5404 // declaration context is dependent but does not refer to a class,
5405 // class template, or class template partial specialization. Complain
5406 // and return early, to avoid the coming semantic disaster.
5407 Diag(D.getIdentifierLoc(),
5408 diag::err_template_qualified_declarator_no_match)
5409 << D.getCXXScopeSpec().getScopeRep()
5410 << D.getCXXScopeSpec().getRange();
5411 return nullptr;
5412 }
5413 bool IsDependentContext = DC->isDependentContext();
5414
5415 if (!IsDependentContext &&
5416 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5417 return nullptr;
5418
5419 // If a class is incomplete, do not parse entities inside it.
5420 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5421 Diag(D.getIdentifierLoc(),
5422 diag::err_member_def_undefined_record)
5423 << Name << DC << D.getCXXScopeSpec().getRange();
5424 return nullptr;
5425 }
5426 if (!D.getDeclSpec().isFriendSpecified()) {
5427 if (diagnoseQualifiedDeclaration(
5428 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5429 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5430 if (DC->isRecord())
5431 return nullptr;
5432
5433 D.setInvalidType();
5434 }
5435 }
5436
5437 // Check whether we need to rebuild the type of the given
5438 // declaration in the current instantiation.
5439 if (EnteringContext && IsDependentContext &&
5440 TemplateParamLists.size() != 0) {
5441 ContextRAII SavedContext(*this, DC);
5442 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5443 D.setInvalidType();
5444 }
5445 }
5446
5447 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5448 QualType R = TInfo->getType();
5449
5450 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5451 UPPC_DeclarationType))
5452 D.setInvalidType();
5453
5454 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5455 forRedeclarationInCurContext());
5456
5457 // See if this is a redefinition of a variable in the same scope.
5458 if (!D.getCXXScopeSpec().isSet()) {
5459 bool IsLinkageLookup = false;
5460 bool CreateBuiltins = false;
5461
5462 // If the declaration we're planning to build will be a function
5463 // or object with linkage, then look for another declaration with
5464 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5465 //
5466 // If the declaration we're planning to build will be declared with
5467 // external linkage in the translation unit, create any builtin with
5468 // the same name.
5469 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5470 /* Do nothing*/;
5471 else if (CurContext->isFunctionOrMethod() &&
5472 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5473 R->isFunctionType())) {
5474 IsLinkageLookup = true;
5475 CreateBuiltins =
5476 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5477 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5478 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5479 CreateBuiltins = true;
5480
5481 if (IsLinkageLookup) {
5482 Previous.clear(LookupRedeclarationWithLinkage);
5483 Previous.setRedeclarationKind(ForExternalRedeclaration);
5484 }
5485
5486 LookupName(Previous, S, CreateBuiltins);
5487 } else { // Something like "int foo::x;"
5488 LookupQualifiedName(Previous, DC);
5489
5490 // C++ [dcl.meaning]p1:
5491 // When the declarator-id is qualified, the declaration shall refer to a
5492 // previously declared member of the class or namespace to which the
5493 // qualifier refers (or, in the case of a namespace, of an element of the
5494 // inline namespace set of that namespace (7.3.1)) or to a specialization
5495 // thereof; [...]
5496 //
5497 // Note that we already checked the context above, and that we do not have
5498 // enough information to make sure that Previous contains the declaration
5499 // we want to match. For example, given:
5500 //
5501 // class X {
5502 // void f();
5503 // void f(float);
5504 // };
5505 //
5506 // void X::f(int) { } // ill-formed
5507 //
5508 // In this case, Previous will point to the overload set
5509 // containing the two f's declared in X, but neither of them
5510 // matches.
5511
5512 // C++ [dcl.meaning]p1:
5513 // [...] the member shall not merely have been introduced by a
5514 // using-declaration in the scope of the class or namespace nominated by
5515 // the nested-name-specifier of the declarator-id.
5516 RemoveUsingDecls(Previous);
5517 }
5518
5519 if (Previous.isSingleResult() &&
5520 Previous.getFoundDecl()->isTemplateParameter()) {
5521 // Maybe we will complain about the shadowed template parameter.
5522 if (!D.isInvalidType())
5523 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5524 Previous.getFoundDecl());
5525
5526 // Just pretend that we didn't see the previous declaration.
5527 Previous.clear();
5528 }
5529
5530 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5531 // Forget that the previous declaration is the injected-class-name.
5532 Previous.clear();
5533
5534 // In C++, the previous declaration we find might be a tag type
5535 // (class or enum). In this case, the new declaration will hide the
5536 // tag type. Note that this applies to functions, function templates, and
5537 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5538 if (Previous.isSingleTagDecl() &&
5539 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5540 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5541 Previous.clear();
5542
5543 // Check that there are no default arguments other than in the parameters
5544 // of a function declaration (C++ only).
5545 if (getLangOpts().CPlusPlus)
5546 CheckExtraCXXDefaultArguments(D);
5547
5548 NamedDecl *New;
5549
5550 bool AddToScope = true;
5551 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5552 if (TemplateParamLists.size()) {
5553 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5554 return nullptr;
5555 }
5556
5557 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5558 } else if (R->isFunctionType()) {
5559 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5560 TemplateParamLists,
5561 AddToScope);
5562 } else {
5563 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5564 AddToScope);
5565 }
5566
5567 if (!New)
5568 return nullptr;
5569
5570 // If this has an identifier and is not a function template specialization,
5571 // add it to the scope stack.
5572 if (New->getDeclName() && AddToScope)
5573 PushOnScopeChains(New, S);
5574
5575 if (isInOpenMPDeclareTargetContext())
5576 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5577
5578 return New;
5579}
5580
5581/// Helper method to turn variable array types into constant array
5582/// types in certain situations which would otherwise be errors (for
5583/// GCC compatibility).
5584static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5585 ASTContext &Context,
5586 bool &SizeIsNegative,
5587 llvm::APSInt &Oversized) {
5588 // This method tries to turn a variable array into a constant
5589 // array even when the size isn't an ICE. This is necessary
5590 // for compatibility with code that depends on gcc's buggy
5591 // constant expression folding, like struct {char x[(int)(char*)2];}
5592 SizeIsNegative = false;
5593 Oversized = 0;
5594
5595 if (T->isDependentType())
5596 return QualType();
5597
5598 QualifierCollector Qs;
5599 const Type *Ty = Qs.strip(T);
5600
5601 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5602 QualType Pointee = PTy->getPointeeType();
5603 QualType FixedType =
5604 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5605 Oversized);
5606 if (FixedType.isNull()) return FixedType;
5607 FixedType = Context.getPointerType(FixedType);
5608 return Qs.apply(Context, FixedType);
5609 }
5610 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5611 QualType Inner = PTy->getInnerType();
5612 QualType FixedType =
5613 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5614 Oversized);
5615 if (FixedType.isNull()) return FixedType;
5616 FixedType = Context.getParenType(FixedType);
5617 return Qs.apply(Context, FixedType);
5618 }
5619
5620 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5621 if (!VLATy)
5622 return QualType();
5623 // FIXME: We should probably handle this case
5624 if (VLATy->getElementType()->isVariablyModifiedType())
5625 return QualType();
5626
5627 Expr::EvalResult Result;
5628 if (!VLATy->getSizeExpr() ||
5629 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5630 return QualType();
5631
5632 llvm::APSInt Res = Result.Val.getInt();
5633
5634 // Check whether the array size is negative.
5635 if (Res.isSigned() && Res.isNegative()) {
5636 SizeIsNegative = true;
5637 return QualType();
5638 }
5639
5640 // Check whether the array is too large to be addressed.
5641 unsigned ActiveSizeBits
5642 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5643 Res);
5644 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5645 Oversized = Res;
5646 return QualType();
5647 }
5648
5649 return Context.getConstantArrayType(VLATy->getElementType(),
5650 Res, ArrayType::Normal, 0);
5651}
5652
5653static void
5654FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5655 SrcTL = SrcTL.getUnqualifiedLoc();
5656 DstTL = DstTL.getUnqualifiedLoc();
5657 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5658 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5659 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5660 DstPTL.getPointeeLoc());
5661 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5662 return;
5663 }
5664 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5665 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5666 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5667 DstPTL.getInnerLoc());
5668 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5669 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5670 return;
5671 }
5672 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5673 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5674 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5675 TypeLoc DstElemTL = DstATL.getElementLoc();
5676 DstElemTL.initializeFullCopy(SrcElemTL);
5677 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5678 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5679 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5680}
5681
5682/// Helper method to turn variable array types into constant array
5683/// types in certain situations which would otherwise be errors (for
5684/// GCC compatibility).
5685static TypeSourceInfo*
5686TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5687 ASTContext &Context,
5688 bool &SizeIsNegative,
5689 llvm::APSInt &Oversized) {
5690 QualType FixedTy
5691 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5692 SizeIsNegative, Oversized);
5693 if (FixedTy.isNull())
5694 return nullptr;
5695 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5696 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5697 FixedTInfo->getTypeLoc());
5698 return FixedTInfo;
5699}
5700
5701/// Register the given locally-scoped extern "C" declaration so
5702/// that it can be found later for redeclarations. We include any extern "C"
5703/// declaration that is not visible in the translation unit here, not just
5704/// function-scope declarations.
5705void
5706Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5707 if (!getLangOpts().CPlusPlus &&
5708 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5709 // Don't need to track declarations in the TU in C.
5710 return;
5711
5712 // Note that we have a locally-scoped external with this name.
5713 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5714}
5715
5716NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5717 // FIXME: We can have multiple results via __attribute__((overloadable)).
5718 auto Result = Context.getExternCContextDecl()->lookup(Name);
5719 return Result.empty() ? nullptr : *Result.begin();
5720}
5721
5722/// Diagnose function specifiers on a declaration of an identifier that
5723/// does not identify a function.
5724void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5725 // FIXME: We should probably indicate the identifier in question to avoid
5726 // confusion for constructs like "virtual int a(), b;"
5727 if (DS.isVirtualSpecified())
5728 Diag(DS.getVirtualSpecLoc(),
5729 diag::err_virtual_non_function);
5730
5731 if (DS.hasExplicitSpecifier())
5732 Diag(DS.getExplicitSpecLoc(),
5733 diag::err_explicit_non_function);
5734
5735 if (DS.isNoreturnSpecified())
5736 Diag(DS.getNoreturnSpecLoc(),
5737 diag::err_noreturn_non_function);
5738}
5739
5740NamedDecl*
5741Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5742 TypeSourceInfo *TInfo, LookupResult &Previous) {
5743 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5744 if (D.getCXXScopeSpec().isSet()) {
5745 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5746 << D.getCXXScopeSpec().getRange();
5747 D.setInvalidType();
5748 // Pretend we didn't see the scope specifier.
5749 DC = CurContext;
5750 Previous.clear();
5751 }
5752
5753 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5754
5755 if (D.getDeclSpec().isInlineSpecified())
5756 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5757 << getLangOpts().CPlusPlus17;
5758 if (D.getDeclSpec().isConstexprSpecified())
5759 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5760 << 1;
5761
5762 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5763 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5764 Diag(D.getName().StartLocation,
5765 diag::err_deduction_guide_invalid_specifier)
5766 << "typedef";
5767 else
5768 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5769 << D.getName().getSourceRange();
5770 return nullptr;
5771 }
5772
5773 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5774 if (!NewTD) return nullptr;
5775
5776 // Handle attributes prior to checking for duplicates in MergeVarDecl
5777 ProcessDeclAttributes(S, NewTD, D);
5778
5779 CheckTypedefForVariablyModifiedType(S, NewTD);
5780
5781 bool Redeclaration = D.isRedeclaration();
5782 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5783 D.setRedeclaration(Redeclaration);
5784 return ND;
5785}
5786
5787void
5788Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5789 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5790 // then it shall have block scope.
5791 // Note that variably modified types must be fixed before merging the decl so
5792 // that redeclarations will match.
5793 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5794 QualType T = TInfo->getType();
5795 if (T->isVariablyModifiedType()) {
5796 setFunctionHasBranchProtectedScope();
5797
5798 if (S->getFnParent() == nullptr) {
5799 bool SizeIsNegative;
5800 llvm::APSInt Oversized;
5801 TypeSourceInfo *FixedTInfo =
5802 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5803 SizeIsNegative,
5804 Oversized);
5805 if (FixedTInfo) {
5806 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5807 NewTD->setTypeSourceInfo(FixedTInfo);
5808 } else {
5809 if (SizeIsNegative)
5810 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5811 else if (T->isVariableArrayType())
5812 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5813 else if (Oversized.getBoolValue())
5814 Diag(NewTD->getLocation(), diag::err_array_too_large)
5815 << Oversized.toString(10);
5816 else
5817 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5818 NewTD->setInvalidDecl();
5819 }
5820 }
5821 }
5822}
5823
5824/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5825/// declares a typedef-name, either using the 'typedef' type specifier or via
5826/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5827NamedDecl*
5828Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5829 LookupResult &Previous, bool &Redeclaration) {
5830
5831 // Find the shadowed declaration before filtering for scope.
5832 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5833
5834 // Merge the decl with the existing one if appropriate. If the decl is
5835 // in an outer scope, it isn't the same thing.
5836 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5837 /*AllowInlineNamespace*/false);
5838 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5839 if (!Previous.empty()) {
5840 Redeclaration = true;
5841 MergeTypedefNameDecl(S, NewTD, Previous);
5842 }
5843
5844 if (ShadowedDecl && !Redeclaration)
5845 CheckShadow(NewTD, ShadowedDecl, Previous);
5846
5847 // If this is the C FILE type, notify the AST context.
5848 if (IdentifierInfo *II = NewTD->getIdentifier())
5849 if (!NewTD->isInvalidDecl() &&
5850 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5851 if (II->isStr("FILE"))
5852 Context.setFILEDecl(NewTD);
5853 else if (II->isStr("jmp_buf"))
5854 Context.setjmp_bufDecl(NewTD);
5855 else if (II->isStr("sigjmp_buf"))
5856 Context.setsigjmp_bufDecl(NewTD);
5857 else if (II->isStr("ucontext_t"))
5858 Context.setucontext_tDecl(NewTD);
5859 else if (II->isStr("pthread_t"))
5860 Context.setpthread_tDecl(NewTD);
5861 else if (II->isStr("pthread_attr_t"))
5862 Context.setpthread_attr_tDecl(NewTD);
5863 }
5864
5865 if (isa<TypedefDecl>(NewTD) && NewTD->hasAttrs())
5866 CheckAlignasUnderalignment(NewTD);
5867
5868 return NewTD;
5869}
5870
5871/// Determines whether the given declaration is an out-of-scope
5872/// previous declaration.
5873///
5874/// This routine should be invoked when name lookup has found a
5875/// previous declaration (PrevDecl) that is not in the scope where a
5876/// new declaration by the same name is being introduced. If the new
5877/// declaration occurs in a local scope, previous declarations with
5878/// linkage may still be considered previous declarations (C99
5879/// 6.2.2p4-5, C++ [basic.link]p6).
5880///
5881/// \param PrevDecl the previous declaration found by name
5882/// lookup
5883///
5884/// \param DC the context in which the new declaration is being
5885/// declared.
5886///
5887/// \returns true if PrevDecl is an out-of-scope previous declaration
5888/// for a new delcaration with the same name.
5889static bool
5890isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5891 ASTContext &Context) {
5892 if (!PrevDecl)
5893 return false;
5894
5895 if (!PrevDecl->hasLinkage())
5896 return false;
5897
5898 if (Context.getLangOpts().CPlusPlus) {
5899 // C++ [basic.link]p6:
5900 // If there is a visible declaration of an entity with linkage
5901 // having the same name and type, ignoring entities declared
5902 // outside the innermost enclosing namespace scope, the block
5903 // scope declaration declares that same entity and receives the
5904 // linkage of the previous declaration.
5905 DeclContext *OuterContext = DC->getRedeclContext();
5906 if (!OuterContext->isFunctionOrMethod())
5907 // This rule only applies to block-scope declarations.
5908 return false;
5909
5910 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5911 if (PrevOuterContext->isRecord())
5912 // We found a member function: ignore it.
5913 return false;
5914
5915 // Find the innermost enclosing namespace for the new and
5916 // previous declarations.
5917 OuterContext = OuterContext->getEnclosingNamespaceContext();
5918 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5919
5920 // The previous declaration is in a different namespace, so it
5921 // isn't the same function.
5922 if (!OuterContext->Equals(PrevOuterContext))
5923 return false;
5924 }
5925
5926 return true;
5927}
5928
5929static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5930 CXXScopeSpec &SS = D.getCXXScopeSpec();
5931 if (!SS.isSet()) return;
5932 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5933}
5934
5935bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5936 QualType type = decl->getType();
5937 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5938 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5939 // Various kinds of declaration aren't allowed to be __autoreleasing.
5940 unsigned kind = -1U;
5941 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5942 if (var->hasAttr<BlocksAttr>())
5943 kind = 0; // __block
5944 else if (!var->hasLocalStorage())
5945 kind = 1; // global
5946 } else if (isa<ObjCIvarDecl>(decl)) {
5947 kind = 3; // ivar
5948 } else if (isa<FieldDecl>(decl)) {
5949 kind = 2; // field
5950 }
5951
5952 if (kind != -1U) {
5953 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5954 << kind;
5955 }
5956 } else if (lifetime == Qualifiers::OCL_None) {
5957 // Try to infer lifetime.
5958 if (!type->isObjCLifetimeType())
5959 return false;
5960
5961 lifetime = type->getObjCARCImplicitLifetime();
5962 type = Context.getLifetimeQualifiedType(type, lifetime);
5963 decl->setType(type);
5964 }
5965
5966 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5967 // Thread-local variables cannot have lifetime.
5968 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5969 var->getTLSKind()) {
5970 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5971 << var->getType();
5972 return true;
5973 }
5974 }
5975
5976 return false;
5977}
5978
5979static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5980 // Ensure that an auto decl is deduced otherwise the checks below might cache
5981 // the wrong linkage.
5982 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5983
5984 // 'weak' only applies to declarations with external linkage.
5985 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5986 if (!ND.isExternallyVisible()) {
5987 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5988 ND.dropAttr<WeakAttr>();
5989 }
5990 }
5991 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5992 if (ND.isExternallyVisible()) {
5993 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5994 ND.dropAttr<WeakRefAttr>();
5995 ND.dropAttr<AliasAttr>();
5996 }
5997 }
5998
5999 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6000 if (VD->hasInit()) {
6001 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6002 assert(VD->isThisDeclarationADefinition() &&
6003 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6004 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6005 VD->dropAttr<AliasAttr>();
6006 }
6007 }
6008 }
6009
6010 // 'selectany' only applies to externally visible variable declarations.
6011 // It does not apply to functions.
6012 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6013 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6014 S.Diag(Attr->getLocation(),
6015 diag::err_attribute_selectany_non_extern_data);
6016 ND.dropAttr<SelectAnyAttr>();
6017 }
6018 }
6019
6020 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6021 auto *VD = dyn_cast<VarDecl>(&ND);
6022 bool IsAnonymousNS = false;
6023 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6024 if (VD) {
6025 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6026 while (NS && !IsAnonymousNS) {
6027 IsAnonymousNS = NS->isAnonymousNamespace();
6028 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6029 }
6030 }
6031 // dll attributes require external linkage. Static locals may have external
6032 // linkage but still cannot be explicitly imported or exported.
6033 // In Microsoft mode, a variable defined in anonymous namespace must have
6034 // external linkage in order to be exported.
6035 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6036 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6037 (!AnonNSInMicrosoftMode &&
6038 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6039 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6040 << &ND << Attr;
6041 ND.setInvalidDecl();
6042 }
6043 }
6044
6045 // Virtual functions cannot be marked as 'notail'.
6046 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6047 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6048 if (MD->isVirtual()) {
6049 S.Diag(ND.getLocation(),
6050 diag::err_invalid_attribute_on_virtual_function)
6051 << Attr;
6052 ND.dropAttr<NotTailCalledAttr>();
6053 }
6054
6055 // Check the attributes on the function type, if any.
6056 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6057 // Don't declare this variable in the second operand of the for-statement;
6058 // GCC miscompiles that by ending its lifetime before evaluating the
6059 // third operand. See gcc.gnu.org/PR86769.
6060 AttributedTypeLoc ATL;
6061 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6062 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6063 TL = ATL.getModifiedLoc()) {
6064 // The [[lifetimebound]] attribute can be applied to the implicit object
6065 // parameter of a non-static member function (other than a ctor or dtor)
6066 // by applying it to the function type.
6067 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6068 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6069 if (!MD || MD->isStatic()) {
6070 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6071 << !MD << A->getRange();
6072 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6073 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6074 << isa<CXXDestructorDecl>(MD) << A->getRange();
6075 }
6076 }
6077 }
6078 }
6079}
6080
6081static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6082 NamedDecl *NewDecl,
6083 bool IsSpecialization,
6084 bool IsDefinition) {
6085 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6086 return;
6087
6088 bool IsTemplate = false;
6089 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6090 OldDecl = OldTD->getTemplatedDecl();
6091 IsTemplate = true;
6092 if (!IsSpecialization)
6093 IsDefinition = false;
6094 }
6095 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6096 NewDecl = NewTD->getTemplatedDecl();
6097 IsTemplate = true;
6098 }
6099
6100 if (!OldDecl || !NewDecl)
6101 return;
6102
6103 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6104 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6105 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6106 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6107
6108 // dllimport and dllexport are inheritable attributes so we have to exclude
6109 // inherited attribute instances.
6110 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6111 (NewExportAttr && !NewExportAttr->isInherited());
6112
6113 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6114 // the only exception being explicit specializations.
6115 // Implicitly generated declarations are also excluded for now because there
6116 // is no other way to switch these to use dllimport or dllexport.
6117 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6118
6119 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6120 // Allow with a warning for free functions and global variables.
6121 bool JustWarn = false;
6122 if (!OldDecl->isCXXClassMember()) {
6123 auto *VD = dyn_cast<VarDecl>(OldDecl);
6124 if (VD && !VD->getDescribedVarTemplate())
6125 JustWarn = true;
6126 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6127 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6128 JustWarn = true;
6129 }
6130
6131 // We cannot change a declaration that's been used because IR has already
6132 // been emitted. Dllimported functions will still work though (modulo
6133 // address equality) as they can use the thunk.
6134 if (OldDecl->isUsed())
6135 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6136 JustWarn = false;
6137
6138 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6139 : diag::err_attribute_dll_redeclaration;
6140 S.Diag(NewDecl->getLocation(), DiagID)
6141 << NewDecl
6142 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6143 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6144 if (!JustWarn) {
6145 NewDecl->setInvalidDecl();
6146 return;
6147 }
6148 }
6149
6150 // A redeclaration is not allowed to drop a dllimport attribute, the only
6151 // exceptions being inline function definitions (except for function
6152 // templates), local extern declarations, qualified friend declarations or
6153 // special MSVC extension: in the last case, the declaration is treated as if
6154 // it were marked dllexport.
6155 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6156 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6157 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6158 // Ignore static data because out-of-line definitions are diagnosed
6159 // separately.
6160 IsStaticDataMember = VD->isStaticDataMember();
6161 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6162 VarDecl::DeclarationOnly;
6163 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6164 IsInline = FD->isInlined();
6165 IsQualifiedFriend = FD->getQualifier() &&
6166 FD->getFriendObjectKind() == Decl::FOK_Declared;
6167 }
6168
6169 if (OldImportAttr && !HasNewAttr &&
6170 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6171 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6172 if (IsMicrosoft && IsDefinition) {
6173 S.Diag(NewDecl->getLocation(),
6174 diag::warn_redeclaration_without_import_attribute)
6175 << NewDecl;
6176 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6177 NewDecl->dropAttr<DLLImportAttr>();
6178 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6179 NewImportAttr->getRange(), S.Context,
6180 NewImportAttr->getSpellingListIndex()));
6181 } else {
6182 S.Diag(NewDecl->getLocation(),
6183 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6184 << NewDecl << OldImportAttr;
6185 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6186 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6187 OldDecl->dropAttr<DLLImportAttr>();
6188 NewDecl->dropAttr<DLLImportAttr>();
6189 }
6190 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6191 // In MinGW, seeing a function declared inline drops the dllimport
6192 // attribute.
6193 OldDecl->dropAttr<DLLImportAttr>();
6194 NewDecl->dropAttr<DLLImportAttr>();
6195 S.Diag(NewDecl->getLocation(),
6196 diag::warn_dllimport_dropped_from_inline_function)
6197 << NewDecl << OldImportAttr;
6198 }
6199
6200 // A specialization of a class template member function is processed here
6201 // since it's a redeclaration. If the parent class is dllexport, the
6202 // specialization inherits that attribute. This doesn't happen automatically
6203 // since the parent class isn't instantiated until later.
6204 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6205 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6206 !NewImportAttr && !NewExportAttr) {
6207 if (const DLLExportAttr *ParentExportAttr =
6208 MD->getParent()->getAttr<DLLExportAttr>()) {
6209 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6210 NewAttr->setInherited(true);
6211 NewDecl->addAttr(NewAttr);
6212 }
6213 }
6214 }
6215}
6216
6217/// Given that we are within the definition of the given function,
6218/// will that definition behave like C99's 'inline', where the
6219/// definition is discarded except for optimization purposes?
6220static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6221 // Try to avoid calling GetGVALinkageForFunction.
6222
6223 // All cases of this require the 'inline' keyword.
6224 if (!FD->isInlined()) return false;
6225
6226 // This is only possible in C++ with the gnu_inline attribute.
6227 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6228 return false;
6229
6230 // Okay, go ahead and call the relatively-more-expensive function.
6231 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6232}
6233
6234/// Determine whether a variable is extern "C" prior to attaching
6235/// an initializer. We can't just call isExternC() here, because that
6236/// will also compute and cache whether the declaration is externally
6237/// visible, which might change when we attach the initializer.
6238///
6239/// This can only be used if the declaration is known to not be a
6240/// redeclaration of an internal linkage declaration.
6241///
6242/// For instance:
6243///
6244/// auto x = []{};
6245///
6246/// Attaching the initializer here makes this declaration not externally
6247/// visible, because its type has internal linkage.
6248///
6249/// FIXME: This is a hack.
6250template<typename T>
6251static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6252 if (S.getLangOpts().CPlusPlus) {
6253 // In C++, the overloadable attribute negates the effects of extern "C".
6254 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6255 return false;
6256
6257 // So do CUDA's host/device attributes.
6258 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6259 D->template hasAttr<CUDAHostAttr>()))
6260 return false;
6261 }
6262 return D->isExternC();
6263}
6264
6265static bool shouldConsiderLinkage(const VarDecl *VD) {
6266 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6267 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6268 isa<OMPDeclareMapperDecl>(DC))
6269 return VD->hasExternalStorage();
6270 if (DC->isFileContext())
6271 return true;
6272 if (DC->isRecord())
6273 return false;
6274 llvm_unreachable("Unexpected context");
6275}
6276
6277static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6278 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6279 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6280 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6281 return true;
6282 if (DC->isRecord())
6283 return false;
6284 llvm_unreachable("Unexpected context");
6285}
6286
6287static bool hasParsedAttr(Scope *S, const Declarator &PD,
6288 ParsedAttr::Kind Kind) {
6289 // Check decl attributes on the DeclSpec.
6290 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6291 return true;
6292
6293 // Walk the declarator structure, checking decl attributes that were in a type
6294 // position to the decl itself.
6295 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6296 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6297 return true;
6298 }
6299
6300 // Finally, check attributes on the decl itself.
6301 return PD.getAttributes().hasAttribute(Kind);
6302}
6303
6304/// Adjust the \c DeclContext for a function or variable that might be a
6305/// function-local external declaration.
6306bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6307 if (!DC->isFunctionOrMethod())
6308 return false;
6309
6310 // If this is a local extern function or variable declared within a function
6311 // template, don't add it into the enclosing namespace scope until it is
6312 // instantiated; it might have a dependent type right now.
6313 if (DC->isDependentContext())
6314 return true;
6315
6316 // C++11 [basic.link]p7:
6317 // When a block scope declaration of an entity with linkage is not found to
6318 // refer to some other declaration, then that entity is a member of the
6319 // innermost enclosing namespace.
6320 //
6321 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6322 // semantically-enclosing namespace, not a lexically-enclosing one.
6323 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6324 DC = DC->getParent();
6325 return true;
6326}
6327
6328/// Returns true if given declaration has external C language linkage.
6329static bool isDeclExternC(const Decl *D) {
6330 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6331 return FD->isExternC();
6332 if (const auto *VD = dyn_cast<VarDecl>(D))
6333 return VD->isExternC();
6334
6335 llvm_unreachable("Unknown type of decl!");
6336}
6337
6338template <typename AttrTy>
6339static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6340 const TypedefNameDecl *TND = TT->getDecl();
6341 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6342 AttrTy *Clone = Attribute->clone(S.Context);
6343 Clone->setInherited(true);
6344 D->addAttr(Clone);
6345 }
6346}
6347
6348NamedDecl *Sema::ActOnVariableDeclarator(
6349 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6350 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6351 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6352 QualType R = TInfo->getType();
6353 DeclarationName Name = GetNameForDeclarator(D).getName();
6354
6355 IdentifierInfo *II = Name.getAsIdentifierInfo();
6356
6357 if (D.isDecompositionDeclarator()) {
6358 // Take the name of the first declarator as our name for diagnostic
6359 // purposes.
6360 auto &Decomp = D.getDecompositionDeclarator();
6361 if (!Decomp.bindings().empty()) {
6362 II = Decomp.bindings()[0].Name;
6363 Name = II;
6364 }
6365 } else if (!II) {
6366 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6367 return nullptr;
6368 }
6369
6370 if (getLangOpts().OpenCL) {
6371 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6372 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6373 // argument.
6374 if (R->isImageType() || R->isPipeType()) {
6375 Diag(D.getIdentifierLoc(),
6376 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6377 << R;
6378 D.setInvalidType();
6379 return nullptr;
6380 }
6381
6382 // OpenCL v1.2 s6.9.r:
6383 // The event type cannot be used to declare a program scope variable.
6384 // OpenCL v2.0 s6.9.q:
6385 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6386 if (NULL == S->getParent()) {
6387 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6388 Diag(D.getIdentifierLoc(),
6389 diag::err_invalid_type_for_program_scope_var) << R;
6390 D.setInvalidType();
6391 return nullptr;
6392 }
6393 }
6394
6395 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6396 QualType NR = R;
6397 while (NR->isPointerType()) {
6398 if (NR->isFunctionPointerType()) {
6399 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6400 D.setInvalidType();
6401 break;
6402 }
6403 NR = NR->getPointeeType();
6404 }
6405
6406 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6407 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6408 // half array type (unless the cl_khr_fp16 extension is enabled).
6409 if (Context.getBaseElementType(R)->isHalfType()) {
6410 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6411 D.setInvalidType();
6412 }
6413 }
6414
6415 if (R->isSamplerT()) {
6416 // OpenCL v1.2 s6.9.b p4:
6417 // The sampler type cannot be used with the __local and __global address
6418 // space qualifiers.
6419 if (R.getAddressSpace() == LangAS::opencl_local ||
6420 R.getAddressSpace() == LangAS::opencl_global) {
6421 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6422 }
6423
6424 // OpenCL v1.2 s6.12.14.1:
6425 // A global sampler must be declared with either the constant address
6426 // space qualifier or with the const qualifier.
6427 if (DC->isTranslationUnit() &&
6428 !(R.getAddressSpace() == LangAS::opencl_constant ||
6429 R.isConstQualified())) {
6430 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6431 D.setInvalidType();
6432 }
6433 }
6434
6435 // OpenCL v1.2 s6.9.r:
6436 // The event type cannot be used with the __local, __constant and __global
6437 // address space qualifiers.
6438 if (R->isEventT()) {
6439 if (R.getAddressSpace() != LangAS::opencl_private) {
6440 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6441 D.setInvalidType();
6442 }
6443 }
6444
6445 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6446 // supported. OpenCL C does not support thread_local either, and
6447 // also reject all other thread storage class specifiers.
6448 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6449 if (TSC != TSCS_unspecified) {
6450 bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6451 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6452 diag::err_opencl_unknown_type_specifier)
6453 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6454 << DeclSpec::getSpecifierName(TSC) << 1;
6455 D.setInvalidType();
6456 return nullptr;
6457 }
6458 }
6459
6460 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6461 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6462
6463 // dllimport globals without explicit storage class are treated as extern. We
6464 // have to change the storage class this early to get the right DeclContext.
6465 if (SC == SC_None && !DC->isRecord() &&
6466 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6467 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6468 SC = SC_Extern;
6469
6470 DeclContext *OriginalDC = DC;
6471 bool IsLocalExternDecl = SC == SC_Extern &&
6472 adjustContextForLocalExternDecl(DC);
6473
6474 if (SCSpec == DeclSpec::SCS_mutable) {
6475 // mutable can only appear on non-static class members, so it's always
6476 // an error here
6477 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6478 D.setInvalidType();
6479 SC = SC_None;
6480 }
6481
6482 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6483 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6484 D.getDeclSpec().getStorageClassSpecLoc())) {
6485 // In C++11, the 'register' storage class specifier is deprecated.
6486 // Suppress the warning in system macros, it's used in macros in some
6487 // popular C system headers, such as in glibc's htonl() macro.
6488 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6489 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6490 : diag::warn_deprecated_register)
6491 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6492 }
6493
6494 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6495
6496 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6497 // C99 6.9p2: The storage-class specifiers auto and register shall not
6498 // appear in the declaration specifiers in an external declaration.
6499 // Global Register+Asm is a GNU extension we support.
6500 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6501 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6502 D.setInvalidType();
6503 }
6504 }
6505
6506 bool IsMemberSpecialization = false;
6507 bool IsVariableTemplateSpecialization = false;
6508 bool IsPartialSpecialization = false;
6509 bool IsVariableTemplate = false;
6510 VarDecl *NewVD = nullptr;
6511 VarTemplateDecl *NewTemplate = nullptr;
6512 TemplateParameterList *TemplateParams = nullptr;
6513 if (!getLangOpts().CPlusPlus) {
6514 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6515 II, R, TInfo, SC);
6516
6517 if (R->getContainedDeducedType())
6518 ParsingInitForAutoVars.insert(NewVD);
6519
6520 if (D.isInvalidType())
6521 NewVD->setInvalidDecl();
6522 } else {
6523 bool Invalid = false;
6524
6525 if (DC->isRecord() && !CurContext->isRecord()) {
6526 // This is an out-of-line definition of a static data member.
6527 switch (SC) {
6528 case SC_None:
6529 break;
6530 case SC_Static:
6531 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6532 diag::err_static_out_of_line)
6533 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6534 break;
6535 case SC_Auto:
6536 case SC_Register:
6537 case SC_Extern:
6538 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6539 // to names of variables declared in a block or to function parameters.
6540 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6541 // of class members
6542
6543 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6544 diag::err_storage_class_for_static_member)
6545 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6546 break;
6547 case SC_PrivateExtern:
6548 llvm_unreachable("C storage class in c++!");
6549 }
6550 }
6551
6552 if (SC == SC_Static && CurContext->isRecord()) {
6553 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6554 if (RD->isLocalClass())
6555 Diag(D.getIdentifierLoc(),
6556 diag::err_static_data_member_not_allowed_in_local_class)
6557 << Name << RD->getDeclName();
6558
6559 // C++98 [class.union]p1: If a union contains a static data member,
6560 // the program is ill-formed. C++11 drops this restriction.
6561 if (RD->isUnion())
6562 Diag(D.getIdentifierLoc(),
6563 getLangOpts().CPlusPlus11
6564 ? diag::warn_cxx98_compat_static_data_member_in_union
6565 : diag::ext_static_data_member_in_union) << Name;
6566 // We conservatively disallow static data members in anonymous structs.
6567 else if (!RD->getDeclName())
6568 Diag(D.getIdentifierLoc(),
6569 diag::err_static_data_member_not_allowed_in_anon_struct)
6570 << Name << RD->isUnion();
6571 }
6572 }
6573
6574 // Match up the template parameter lists with the scope specifier, then
6575 // determine whether we have a template or a template specialization.
6576 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6577 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6578 D.getCXXScopeSpec(),
6579 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6580 ? D.getName().TemplateId
6581 : nullptr,
6582 TemplateParamLists,
6583 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6584
6585 if (TemplateParams) {
6586 if (!TemplateParams->size() &&
6587 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6588 // There is an extraneous 'template<>' for this variable. Complain
6589 // about it, but allow the declaration of the variable.
6590 Diag(TemplateParams->getTemplateLoc(),
6591 diag::err_template_variable_noparams)
6592 << II
6593 << SourceRange(TemplateParams->getTemplateLoc(),
6594 TemplateParams->getRAngleLoc());
6595 TemplateParams = nullptr;
6596 } else {
6597 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6598 // This is an explicit specialization or a partial specialization.
6599 // FIXME: Check that we can declare a specialization here.
6600 IsVariableTemplateSpecialization = true;
6601 IsPartialSpecialization = TemplateParams->size() > 0;
6602 } else { // if (TemplateParams->size() > 0)
6603 // This is a template declaration.
6604 IsVariableTemplate = true;
6605
6606 // Check that we can declare a template here.
6607 if (CheckTemplateDeclScope(S, TemplateParams))
6608 return nullptr;
6609
6610 // Only C++1y supports variable templates (N3651).
6611 Diag(D.getIdentifierLoc(),
6612 getLangOpts().CPlusPlus14
6613 ? diag::warn_cxx11_compat_variable_template
6614 : diag::ext_variable_template);
6615 }
6616 }
6617 } else {
6618 assert((Invalid ||
6619 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6620 "should have a 'template<>' for this decl");
6621 }
6622
6623 if (IsVariableTemplateSpecialization) {
6624 SourceLocation TemplateKWLoc =
6625 TemplateParamLists.size() > 0
6626 ? TemplateParamLists[0]->getTemplateLoc()
6627 : SourceLocation();
6628 DeclResult Res = ActOnVarTemplateSpecialization(
6629 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6630 IsPartialSpecialization);
6631 if (Res.isInvalid())
6632 return nullptr;
6633 NewVD = cast<VarDecl>(Res.get());
6634 AddToScope = false;
6635 } else if (D.isDecompositionDeclarator()) {
6636 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6637 D.getIdentifierLoc(), R, TInfo, SC,
6638 Bindings);
6639 } else
6640 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6641 D.getIdentifierLoc(), II, R, TInfo, SC);
6642
6643 // If this is supposed to be a variable template, create it as such.
6644 if (IsVariableTemplate) {
6645 NewTemplate =
6646 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6647 TemplateParams, NewVD);
6648 NewVD->setDescribedVarTemplate(NewTemplate);
6649 }
6650
6651 // If this decl has an auto type in need of deduction, make a note of the
6652 // Decl so we can diagnose uses of it in its own initializer.
6653 if (R->getContainedDeducedType())
6654 ParsingInitForAutoVars.insert(NewVD);
6655
6656 if (D.isInvalidType() || Invalid) {
6657 NewVD->setInvalidDecl();
6658 if (NewTemplate)
6659 NewTemplate->setInvalidDecl();
6660 }
6661
6662 SetNestedNameSpecifier(*this, NewVD, D);
6663
6664 // If we have any template parameter lists that don't directly belong to
6665 // the variable (matching the scope specifier), store them.
6666 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6667 if (TemplateParamLists.size() > VDTemplateParamLists)
6668 NewVD->setTemplateParameterListsInfo(
6669 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6670
6671 if (D.getDeclSpec().isConstexprSpecified()) {
6672 NewVD->setConstexpr(true);
6673 // C++1z [dcl.spec.constexpr]p1:
6674 // A static data member declared with the constexpr specifier is
6675 // implicitly an inline variable.
6676 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6677 NewVD->setImplicitlyInline();
6678 }
6679 }
6680
6681 if (D.getDeclSpec().isInlineSpecified()) {
6682 if (!getLangOpts().CPlusPlus) {
6683 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6684 << 0;
6685 } else if (CurContext->isFunctionOrMethod()) {
6686 // 'inline' is not allowed on block scope variable declaration.
6687 Diag(D.getDeclSpec().getInlineSpecLoc(),
6688 diag::err_inline_declaration_block_scope) << Name
6689 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6690 } else {
6691 Diag(D.getDeclSpec().getInlineSpecLoc(),
6692 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6693 : diag::ext_inline_variable);
6694 NewVD->setInlineSpecified();
6695 }
6696 }
6697
6698 // Set the lexical context. If the declarator has a C++ scope specifier, the
6699 // lexical context will be different from the semantic context.
6700 NewVD->setLexicalDeclContext(CurContext);
6701 if (NewTemplate)
6702 NewTemplate->setLexicalDeclContext(CurContext);
6703
6704 if (IsLocalExternDecl) {
6705 if (D.isDecompositionDeclarator())
6706 for (auto *B : Bindings)
6707 B->setLocalExternDecl();
6708 else
6709 NewVD->setLocalExternDecl();
6710 }
6711
6712 bool EmitTLSUnsupportedError = false;
6713 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6714 // C++11 [dcl.stc]p4:
6715 // When thread_local is applied to a variable of block scope the
6716 // storage-class-specifier static is implied if it does not appear
6717 // explicitly.
6718 // Core issue: 'static' is not implied if the variable is declared
6719 // 'extern'.
6720 if (NewVD->hasLocalStorage() &&
6721 (SCSpec != DeclSpec::SCS_unspecified ||
6722 TSCS != DeclSpec::TSCS_thread_local ||
6723 !DC->isFunctionOrMethod()))
6724 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6725 diag::err_thread_non_global)
6726 << DeclSpec::getSpecifierName(TSCS);
6727 else if (!Context.getTargetInfo().isTLSSupported()) {
6728 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6729 // Postpone error emission until we've collected attributes required to
6730 // figure out whether it's a host or device variable and whether the
6731 // error should be ignored.
6732 EmitTLSUnsupportedError = true;
6733 // We still need to mark the variable as TLS so it shows up in AST with
6734 // proper storage class for other tools to use even if we're not going
6735 // to emit any code for it.
6736 NewVD->setTSCSpec(TSCS);
6737 } else
6738 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6739 diag::err_thread_unsupported);
6740 } else
6741 NewVD->setTSCSpec(TSCS);
6742 }
6743
6744 // C99 6.7.4p3
6745 // An inline definition of a function with external linkage shall
6746 // not contain a definition of a modifiable object with static or
6747 // thread storage duration...
6748 // We only apply this when the function is required to be defined
6749 // elsewhere, i.e. when the function is not 'extern inline'. Note
6750 // that a local variable with thread storage duration still has to
6751 // be marked 'static'. Also note that it's possible to get these
6752 // semantics in C++ using __attribute__((gnu_inline)).
6753 if (SC == SC_Static && S->getFnParent() != nullptr &&
6754 !NewVD->getType().isConstQualified()) {
6755 FunctionDecl *CurFD = getCurFunctionDecl();
6756 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6757 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6758 diag::warn_static_local_in_extern_inline);
6759 MaybeSuggestAddingStaticToDecl(CurFD);
6760 }
6761 }
6762
6763 if (D.getDeclSpec().isModulePrivateSpecified()) {
6764 if (IsVariableTemplateSpecialization)
6765 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6766 << (IsPartialSpecialization ? 1 : 0)
6767 << FixItHint::CreateRemoval(
6768 D.getDeclSpec().getModulePrivateSpecLoc());
6769 else if (IsMemberSpecialization)
6770 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6771 << 2
6772 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6773 else if (NewVD->hasLocalStorage())
6774 Diag(NewVD->getLocation(), diag::err_module_private_local)
6775 << 0 << NewVD->getDeclName()
6776 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6777 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6778 else {
6779 NewVD->setModulePrivate();
6780 if (NewTemplate)
6781 NewTemplate->setModulePrivate();
6782 for (auto *B : Bindings)
6783 B->setModulePrivate();
6784 }
6785 }
6786
6787 // Handle attributes prior to checking for duplicates in MergeVarDecl
6788 ProcessDeclAttributes(S, NewVD, D);
6789
6790 // FIXME: this is probably the wrong location to be doing this and we should
6791 // probably be doing this for more attributes (especially for function
6792 // pointer attributes (such as format, warn_unused_result, etc)
6793 if (R->isFunctionPointerType())
6794 if (const auto* TT = R->getAs<TypedefType>())
6795 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
6796
6797
6798 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6799 if (EmitTLSUnsupportedError &&
6800 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6801 (getLangOpts().OpenMPIsDevice &&
6802 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6803 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6804 diag::err_thread_unsupported);
6805 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6806 // storage [duration]."
6807 if (SC == SC_None && S->getFnParent() != nullptr &&
6808 (NewVD->hasAttr<CUDASharedAttr>() ||
6809 NewVD->hasAttr<CUDAConstantAttr>())) {
6810 NewVD->setStorageClass(SC_Static);
6811 }
6812 }
6813
6814 // Ensure that dllimport globals without explicit storage class are treated as
6815 // extern. The storage class is set above using parsed attributes. Now we can
6816 // check the VarDecl itself.
6817 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6818 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6819 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6820
6821 // In auto-retain/release, infer strong retension for variables of
6822 // retainable type.
6823 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6824 NewVD->setInvalidDecl();
6825
6826 // Handle GNU asm-label extension (encoded as an attribute).
6827 if (Expr *E = (Expr*)D.getAsmLabel()) {
6828 // The parser guarantees this is a string.
6829 StringLiteral *SE = cast<StringLiteral>(E);
6830 StringRef Label = SE->getString();
6831 if (S->getFnParent() != nullptr) {
6832 switch (SC) {
6833 case SC_None:
6834 case SC_Auto:
6835 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6836 break;
6837 case SC_Register:
6838 // Local Named register
6839 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6840 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6841 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6842 break;
6843 case SC_Static:
6844 case SC_Extern:
6845 case SC_PrivateExtern:
6846 break;
6847 }
6848 } else if (SC == SC_Register) {
6849 // Global Named register
6850 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6851 const auto &TI = Context.getTargetInfo();
6852 bool HasSizeMismatch;
6853
6854 if (!TI.isValidGCCRegisterName(Label))
6855 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6856 else if (!TI.validateGlobalRegisterVariable(Label,
6857 Context.getTypeSize(R),
6858 HasSizeMismatch))
6859 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6860 else if (HasSizeMismatch)
6861 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6862 }
6863
6864 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6865 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6866 NewVD->setInvalidDecl(true);
6867 }
6868 }
6869
6870 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6871 Context, Label, 0));
6872 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6873 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6874 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6875 if (I != ExtnameUndeclaredIdentifiers.end()) {
6876 if (isDeclExternC(NewVD)) {
6877 NewVD->addAttr(I->second);
6878 ExtnameUndeclaredIdentifiers.erase(I);
6879 } else
6880 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6881 << /*Variable*/1 << NewVD;
6882 }
6883 }
6884
6885 // Find the shadowed declaration before filtering for scope.
6886 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6887 ? getShadowedDeclaration(NewVD, Previous)
6888 : nullptr;
6889
6890 // Don't consider existing declarations that are in a different
6891 // scope and are out-of-semantic-context declarations (if the new
6892 // declaration has linkage).
6893 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6894 D.getCXXScopeSpec().isNotEmpty() ||
6895 IsMemberSpecialization ||
6896 IsVariableTemplateSpecialization);
6897
6898 // Check whether the previous declaration is in the same block scope. This
6899 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6900 if (getLangOpts().CPlusPlus &&
6901 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6902 NewVD->setPreviousDeclInSameBlockScope(
6903 Previous.isSingleResult() && !Previous.isShadowed() &&
6904 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6905
6906 if (!getLangOpts().CPlusPlus) {
6907 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6908 } else {
6909 // If this is an explicit specialization of a static data member, check it.
6910 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6911 CheckMemberSpecialization(NewVD, Previous))
6912 NewVD->setInvalidDecl();
6913
6914 // Merge the decl with the existing one if appropriate.
6915 if (!Previous.empty()) {
6916 if (Previous.isSingleResult() &&
6917 isa<FieldDecl>(Previous.getFoundDecl()) &&
6918 D.getCXXScopeSpec().isSet()) {
6919 // The user tried to define a non-static data member
6920 // out-of-line (C++ [dcl.meaning]p1).
6921 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6922 << D.getCXXScopeSpec().getRange();
6923 Previous.clear();
6924 NewVD->setInvalidDecl();
6925 }
6926 } else if (D.getCXXScopeSpec().isSet()) {
6927 // No previous declaration in the qualifying scope.
6928 Diag(D.getIdentifierLoc(), diag::err_no_member)
6929 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6930 << D.getCXXScopeSpec().getRange();
6931 NewVD->setInvalidDecl();
6932 }
6933
6934 if (!IsVariableTemplateSpecialization)
6935 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6936
6937 if (NewTemplate) {
6938 VarTemplateDecl *PrevVarTemplate =
6939 NewVD->getPreviousDecl()
6940 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6941 : nullptr;
6942
6943 // Check the template parameter list of this declaration, possibly
6944 // merging in the template parameter list from the previous variable
6945 // template declaration.
6946 if (CheckTemplateParameterList(
6947 TemplateParams,
6948 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6949 : nullptr,
6950 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6951 DC->isDependentContext())
6952 ? TPC_ClassTemplateMember
6953 : TPC_VarTemplate))
6954 NewVD->setInvalidDecl();
6955
6956 // If we are providing an explicit specialization of a static variable
6957 // template, make a note of that.
6958 if (PrevVarTemplate &&
6959 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6960 PrevVarTemplate->setMemberSpecialization();
6961 }
6962 }
6963
6964 // Diagnose shadowed variables iff this isn't a redeclaration.
6965 if (ShadowedDecl && !D.isRedeclaration())
6966 CheckShadow(NewVD, ShadowedDecl, Previous);
6967
6968 ProcessPragmaWeak(S, NewVD);
6969
6970 // If this is the first declaration of an extern C variable, update
6971 // the map of such variables.
6972 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6973 isIncompleteDeclExternC(*this, NewVD))
6974 RegisterLocallyScopedExternCDecl(NewVD, S);
6975
6976 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6977 Decl *ManglingContextDecl;
6978 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6979 NewVD->getDeclContext(), ManglingContextDecl)) {
6980 Context.setManglingNumber(
6981 NewVD, MCtx->getManglingNumber(
6982 NewVD, getMSManglingNumber(getLangOpts(), S)));
6983 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6984 }
6985 }
6986
6987 // Special handling of variable named 'main'.
6988 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6989 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6990 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6991
6992 // C++ [basic.start.main]p3
6993 // A program that declares a variable main at global scope is ill-formed.
6994 if (getLangOpts().CPlusPlus)
6995 Diag(D.getBeginLoc(), diag::err_main_global_variable);
6996
6997 // In C, and external-linkage variable named main results in undefined
6998 // behavior.
6999 else if (NewVD->hasExternalFormalLinkage())
7000 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7001 }
7002
7003 if (D.isRedeclaration() && !Previous.empty()) {
7004 NamedDecl *Prev = Previous.getRepresentativeDecl();
7005 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7006 D.isFunctionDefinition());
7007 }
7008
7009 if (NewTemplate) {
7010 if (NewVD->isInvalidDecl())
7011 NewTemplate->setInvalidDecl();
7012 ActOnDocumentableDecl(NewTemplate);
7013 return NewTemplate;
7014 }
7015
7016 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7017 CompleteMemberSpecialization(NewVD, Previous);
7018
7019 return NewVD;
7020}
7021
7022/// Enum describing the %select options in diag::warn_decl_shadow.
7023enum ShadowedDeclKind {
7024 SDK_Local,
7025 SDK_Global,
7026 SDK_StaticMember,
7027 SDK_Field,
7028 SDK_Typedef,
7029 SDK_Using
7030};
7031
7032/// Determine what kind of declaration we're shadowing.
7033static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7034 const DeclContext *OldDC) {
7035 if (isa<TypeAliasDecl>(ShadowedDecl))
7036 return SDK_Using;
7037 else if (isa<TypedefDecl>(ShadowedDecl))
7038 return SDK_Typedef;
7039 else if (isa<RecordDecl>(OldDC))
7040 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7041
7042 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7043}
7044
7045/// Return the location of the capture if the given lambda captures the given
7046/// variable \p VD, or an invalid source location otherwise.
7047static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7048 const VarDecl *VD) {
7049 for (const Capture &Capture : LSI->Captures) {
7050 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7051 return Capture.getLocation();
7052 }
7053 return SourceLocation();
7054}
7055
7056static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7057 const LookupResult &R) {
7058 // Only diagnose if we're shadowing an unambiguous field or variable.
7059 if (R.getResultKind() != LookupResult::Found)
7060 return false;
7061
7062 // Return false if warning is ignored.
7063 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7064}
7065
7066/// Return the declaration shadowed by the given variable \p D, or null
7067/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7068NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7069 const LookupResult &R) {
7070 if (!shouldWarnIfShadowedDecl(Diags, R))
7071 return nullptr;
7072
7073 // Don't diagnose declarations at file scope.
7074 if (D->hasGlobalStorage())
7075 return nullptr;
7076
7077 NamedDecl *ShadowedDecl = R.getFoundDecl();
7078 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7079 ? ShadowedDecl
7080 : nullptr;
7081}
7082
7083/// Return the declaration shadowed by the given typedef \p D, or null
7084/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7085NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7086 const LookupResult &R) {
7087 // Don't warn if typedef declaration is part of a class
7088 if (D->getDeclContext()->isRecord())
7089 return nullptr;
7090
7091 if (!shouldWarnIfShadowedDecl(Diags, R))
7092 return nullptr;
7093
7094 NamedDecl *ShadowedDecl = R.getFoundDecl();
7095 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7096}
7097
7098/// Diagnose variable or built-in function shadowing. Implements
7099/// -Wshadow.
7100///
7101/// This method is called whenever a VarDecl is added to a "useful"
7102/// scope.
7103///
7104/// \param ShadowedDecl the declaration that is shadowed by the given variable
7105/// \param R the lookup of the name
7106///
7107void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7108 const LookupResult &R) {
7109 DeclContext *NewDC = D->getDeclContext();
7110
7111 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7112 // Fields are not shadowed by variables in C++ static methods.
7113 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7114 if (MD->isStatic())
7115 return;
7116
7117 // Fields shadowed by constructor parameters are a special case. Usually
7118 // the constructor initializes the field with the parameter.
7119 if (isa<CXXConstructorDecl>(NewDC))
7120 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7121 // Remember that this was shadowed so we can either warn about its
7122 // modification or its existence depending on warning settings.
7123 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7124 return;
7125 }
7126 }
7127
7128 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7129 if (shadowedVar->isExternC()) {
7130 // For shadowing external vars, make sure that we point to the global
7131 // declaration, not a locally scoped extern declaration.
7132 for (auto I : shadowedVar->redecls())
7133 if (I->isFileVarDecl()) {
7134 ShadowedDecl = I;
7135 break;
7136 }
7137 }
7138
7139 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7140
7141 unsigned WarningDiag = diag::warn_decl_shadow;
7142 SourceLocation CaptureLoc;
7143 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7144 isa<CXXMethodDecl>(NewDC)) {
7145 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7146 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7147 if (RD->getLambdaCaptureDefault() == LCD_None) {
7148 // Try to avoid warnings for lambdas with an explicit capture list.
7149 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7150 // Warn only when the lambda captures the shadowed decl explicitly.
7151 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7152 if (CaptureLoc.isInvalid())
7153 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7154 } else {
7155 // Remember that this was shadowed so we can avoid the warning if the
7156 // shadowed decl isn't captured and the warning settings allow it.
7157 cast<LambdaScopeInfo>(getCurFunction())
7158 ->ShadowingDecls.push_back(
7159 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7160 return;
7161 }
7162 }
7163
7164 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7165 // A variable can't shadow a local variable in an enclosing scope, if
7166 // they are separated by a non-capturing declaration context.
7167 for (DeclContext *ParentDC = NewDC;
7168 ParentDC && !ParentDC->Equals(OldDC);
7169 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7170 // Only block literals, captured statements, and lambda expressions
7171 // can capture; other scopes don't.
7172 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7173 !isLambdaCallOperator(ParentDC)) {
7174 return;
7175 }
7176 }
7177 }
7178 }
7179 }
7180
7181 // Only warn about certain kinds of shadowing for class members.
7182 if (NewDC && NewDC->isRecord()) {
7183 // In particular, don't warn about shadowing non-class members.
7184 if (!OldDC->isRecord())
7185 return;
7186
7187 // TODO: should we warn about static data members shadowing
7188 // static data members from base classes?
7189
7190 // TODO: don't diagnose for inaccessible shadowed members.
7191 // This is hard to do perfectly because we might friend the
7192 // shadowing context, but that's just a false negative.
7193 }
7194
7195
7196 DeclarationName Name = R.getLookupName();
7197
7198 // Emit warning and note.
7199 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7200 return;
7201 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7202 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7203 if (!CaptureLoc.isInvalid())
7204 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7205 << Name << /*explicitly*/ 1;
7206 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7207}
7208
7209/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7210/// when these variables are captured by the lambda.
7211void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7212 for (const auto &Shadow : LSI->ShadowingDecls) {
7213 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7214 // Try to avoid the warning when the shadowed decl isn't captured.
7215 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7216 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7217 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7218 ? diag::warn_decl_shadow_uncaptured_local
7219 : diag::warn_decl_shadow)
7220 << Shadow.VD->getDeclName()
7221 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7222 if (!CaptureLoc.isInvalid())
7223 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7224 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7225 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7226 }
7227}
7228
7229/// Check -Wshadow without the advantage of a previous lookup.
7230void Sema::CheckShadow(Scope *S, VarDecl *D) {
7231 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7232 return;
7233
7234 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7235 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7236 LookupName(R, S);
7237 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7238 CheckShadow(D, ShadowedDecl, R);
7239}
7240
7241/// Check if 'E', which is an expression that is about to be modified, refers
7242/// to a constructor parameter that shadows a field.
7243void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7244 // Quickly ignore expressions that can't be shadowing ctor parameters.
7245 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7246 return;
7247 E = E->IgnoreParenImpCasts();
7248 auto *DRE = dyn_cast<DeclRefExpr>(E);
7249 if (!DRE)
7250 return;
7251 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7252 auto I = ShadowingDecls.find(D);
7253 if (I == ShadowingDecls.end())
7254 return;
7255 const NamedDecl *ShadowedDecl = I->second;
7256 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7257 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7258 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7259 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7260
7261 // Avoid issuing multiple warnings about the same decl.
7262 ShadowingDecls.erase(I);
7263}
7264
7265/// Check for conflict between this global or extern "C" declaration and
7266/// previous global or extern "C" declarations. This is only used in C++.
7267template<typename T>
7268static bool checkGlobalOrExternCConflict(
7269 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7270 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7271 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7272
7273 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7274 // The common case: this global doesn't conflict with any extern "C"
7275 // declaration.
7276 return false;
7277 }
7278
7279 if (Prev) {
7280 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7281 // Both the old and new declarations have C language linkage. This is a
7282 // redeclaration.
7283 Previous.clear();
7284 Previous.addDecl(Prev);
7285 return true;
7286 }
7287
7288 // This is a global, non-extern "C" declaration, and there is a previous
7289 // non-global extern "C" declaration. Diagnose if this is a variable
7290 // declaration.
7291 if (!isa<VarDecl>(ND))
7292 return false;
7293 } else {
7294 // The declaration is extern "C". Check for any declaration in the
7295 // translation unit which might conflict.
7296 if (IsGlobal) {
7297 // We have already performed the lookup into the translation unit.
7298 IsGlobal = false;
7299 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7300 I != E; ++I) {
7301 if (isa<VarDecl>(*I)) {
7302 Prev = *I;
7303 break;
7304 }
7305 }
7306 } else {
7307 DeclContext::lookup_result R =
7308 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7309 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7310 I != E; ++I) {
7311 if (isa<VarDecl>(*I)) {
7312 Prev = *I;
7313 break;
7314 }
7315 // FIXME: If we have any other entity with this name in global scope,
7316 // the declaration is ill-formed, but that is a defect: it breaks the
7317 // 'stat' hack, for instance. Only variables can have mangled name
7318 // clashes with extern "C" declarations, so only they deserve a
7319 // diagnostic.
7320 }
7321 }
7322
7323 if (!Prev)
7324 return false;
7325 }
7326
7327 // Use the first declaration's location to ensure we point at something which
7328 // is lexically inside an extern "C" linkage-spec.
7329 assert(Prev && "should have found a previous declaration to diagnose");
7330 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7331 Prev = FD->getFirstDecl();
7332 else
7333 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7334
7335 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7336 << IsGlobal << ND;
7337 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7338 << IsGlobal;
7339 return false;
7340}
7341
7342/// Apply special rules for handling extern "C" declarations. Returns \c true
7343/// if we have found that this is a redeclaration of some prior entity.
7344///
7345/// Per C++ [dcl.link]p6:
7346/// Two declarations [for a function or variable] with C language linkage
7347/// with the same name that appear in different scopes refer to the same
7348/// [entity]. An entity with C language linkage shall not be declared with
7349/// the same name as an entity in global scope.
7350template<typename T>
7351static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7352 LookupResult &Previous) {
7353 if (!S.getLangOpts().CPlusPlus) {
7354 // In C, when declaring a global variable, look for a corresponding 'extern'
7355 // variable declared in function scope. We don't need this in C++, because
7356 // we find local extern decls in the surrounding file-scope DeclContext.
7357 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7358 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7359 Previous.clear();
7360 Previous.addDecl(Prev);
7361 return true;
7362 }
7363 }
7364 return false;
7365 }
7366
7367 // A declaration in the translation unit can conflict with an extern "C"
7368 // declaration.
7369 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7370 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7371
7372 // An extern "C" declaration can conflict with a declaration in the
7373 // translation unit or can be a redeclaration of an extern "C" declaration
7374 // in another scope.
7375 if (isIncompleteDeclExternC(S,ND))
7376 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7377
7378 // Neither global nor extern "C": nothing to do.
7379 return false;
7380}
7381
7382void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7383 // If the decl is already known invalid, don't check it.
7384 if (NewVD->isInvalidDecl())
7385 return;
7386
7387 QualType T = NewVD->getType();
7388
7389 // Defer checking an 'auto' type until its initializer is attached.
7390 if (T->isUndeducedType())
7391 return;
7392
7393 if (NewVD->hasAttrs())
7394 CheckAlignasUnderalignment(NewVD);
7395
7396 if (T->isObjCObjectType()) {
7397 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7398 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7399 T = Context.getObjCObjectPointerType(T);
7400 NewVD->setType(T);
7401 }
7402
7403 // Emit an error if an address space was applied to decl with local storage.
7404 // This includes arrays of objects with address space qualifiers, but not
7405 // automatic variables that point to other address spaces.
7406 // ISO/IEC TR 18037 S5.1.2
7407 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7408 T.getAddressSpace() != LangAS::Default) {
7409 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7410 NewVD->setInvalidDecl();
7411 return;
7412 }
7413
7414 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7415 // scope.
7416 if (getLangOpts().OpenCLVersion == 120 &&
7417 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7418 NewVD->isStaticLocal()) {
7419 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7420 NewVD->setInvalidDecl();
7421 return;
7422 }
7423
7424 if (getLangOpts().OpenCL) {
7425 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7426 if (NewVD->hasAttr<BlocksAttr>()) {
7427 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7428 return;
7429 }
7430
7431 if (T->isBlockPointerType()) {
7432 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7433 // can't use 'extern' storage class.
7434 if (!T.isConstQualified()) {
7435 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7436 << 0 /*const*/;
7437 NewVD->setInvalidDecl();
7438 return;
7439 }
7440 if (NewVD->hasExternalStorage()) {
7441 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7442 NewVD->setInvalidDecl();
7443 return;
7444 }
7445 }
7446 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7447 // __constant address space.
7448 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7449 // variables inside a function can also be declared in the global
7450 // address space.
7451 // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7452 // address space additionally.
7453 // FIXME: Add local AS for OpenCL C++.
7454 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7455 NewVD->hasExternalStorage()) {
7456 if (!T->isSamplerT() &&
7457 !(T.getAddressSpace() == LangAS::opencl_constant ||
7458 (T.getAddressSpace() == LangAS::opencl_global &&
7459 (getLangOpts().OpenCLVersion == 200 ||
7460 getLangOpts().OpenCLCPlusPlus)))) {
7461 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7462 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7463 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7464 << Scope << "global or constant";
7465 else
7466 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7467 << Scope << "constant";
7468 NewVD->setInvalidDecl();
7469 return;
7470 }
7471 } else {
7472 if (T.getAddressSpace() == LangAS::opencl_global) {
7473 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7474 << 1 /*is any function*/ << "global";
7475 NewVD->setInvalidDecl();
7476 return;
7477 }
7478 if (T.getAddressSpace() == LangAS::opencl_constant ||
7479 T.getAddressSpace() == LangAS::opencl_local) {
7480 FunctionDecl *FD = getCurFunctionDecl();
7481 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7482 // in functions.
7483 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7484 if (T.getAddressSpace() == LangAS::opencl_constant)
7485 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7486 << 0 /*non-kernel only*/ << "constant";
7487 else
7488 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7489 << 0 /*non-kernel only*/ << "local";
7490 NewVD->setInvalidDecl();
7491 return;
7492 }
7493 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7494 // in the outermost scope of a kernel function.
7495 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7496 if (!getCurScope()->isFunctionScope()) {
7497 if (T.getAddressSpace() == LangAS::opencl_constant)
7498 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7499 << "constant";
7500 else
7501 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7502 << "local";
7503 NewVD->setInvalidDecl();
7504 return;
7505 }
7506 }
7507 } else if (T.getAddressSpace() != LangAS::opencl_private) {
7508 // Do not allow other address spaces on automatic variable.
7509 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7510 NewVD->setInvalidDecl();
7511 return;
7512 }
7513 }
7514 }
7515
7516 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7517 && !NewVD->hasAttr<BlocksAttr>()) {
7518 if (getLangOpts().getGC() != LangOptions::NonGC)
7519 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7520 else {
7521 assert(!getLangOpts().ObjCAutoRefCount);
7522 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7523 }
7524 }
7525
7526 bool isVM = T->isVariablyModifiedType();
7527 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7528 NewVD->hasAttr<BlocksAttr>())
7529 setFunctionHasBranchProtectedScope();
7530
7531 if ((isVM && NewVD->hasLinkage()) ||
7532 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7533 bool SizeIsNegative;
7534 llvm::APSInt Oversized;
7535 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7536 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7537 QualType FixedT;
7538 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7539 FixedT = FixedTInfo->getType();
7540 else if (FixedTInfo) {
7541 // Type and type-as-written are canonically different. We need to fix up
7542 // both types separately.
7543 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7544 Oversized);
7545 }
7546 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7547 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7548 // FIXME: This won't give the correct result for
7549 // int a[10][n];
7550 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7551
7552 if (NewVD->isFileVarDecl())
7553 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7554 << SizeRange;
7555 else if (NewVD->isStaticLocal())
7556 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7557 << SizeRange;
7558 else
7559 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7560 << SizeRange;
7561 NewVD->setInvalidDecl();
7562 return;
7563 }
7564
7565 if (!FixedTInfo) {
7566 if (NewVD->isFileVarDecl())
7567 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7568 else
7569 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7570 NewVD->setInvalidDecl();
7571 return;
7572 }
7573
7574 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7575 NewVD->setType(FixedT);
7576 NewVD->setTypeSourceInfo(FixedTInfo);
7577 }
7578
7579 if (T->isVoidType()) {
7580 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7581 // of objects and functions.
7582 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7583 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7584 << T;
7585 NewVD->setInvalidDecl();
7586 return;
7587 }
7588 }
7589
7590 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7591 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7592 NewVD->setInvalidDecl();
7593 return;
7594 }
7595
7596 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7597 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7598 NewVD->setInvalidDecl();
7599 return;
7600 }
7601
7602 if (NewVD->isConstexpr() && !T->isDependentType() &&
7603 RequireLiteralType(NewVD->getLocation(), T,
7604 diag::err_constexpr_var_non_literal)) {
7605 NewVD->setInvalidDecl();
7606 return;
7607 }
7608}
7609
7610/// Perform semantic checking on a newly-created variable
7611/// declaration.
7612///
7613/// This routine performs all of the type-checking required for a
7614/// variable declaration once it has been built. It is used both to
7615/// check variables after they have been parsed and their declarators
7616/// have been translated into a declaration, and to check variables
7617/// that have been instantiated from a template.
7618///
7619/// Sets NewVD->isInvalidDecl() if an error was encountered.
7620///
7621/// Returns true if the variable declaration is a redeclaration.
7622bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7623 CheckVariableDeclarationType(NewVD);
7624
7625 // If the decl is already known invalid, don't check it.
7626 if (NewVD->isInvalidDecl())
7627 return false;
7628
7629 // If we did not find anything by this name, look for a non-visible
7630 // extern "C" declaration with the same name.
7631 if (Previous.empty() &&
7632 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7633 Previous.setShadowed();
7634
7635 if (!Previous.empty()) {
7636 MergeVarDecl(NewVD, Previous);
7637 return true;
7638 }
7639 return false;
7640}
7641
7642namespace {
7643struct FindOverriddenMethod {
7644 Sema *S;
7645 CXXMethodDecl *Method;
7646
7647 /// Member lookup function that determines whether a given C++
7648 /// method overrides a method in a base class, to be used with
7649 /// CXXRecordDecl::lookupInBases().
7650 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7651 RecordDecl *BaseRecord =
7652 Specifier->getType()->getAs<RecordType>()->getDecl();
7653
7654 DeclarationName Name = Method->getDeclName();
7655
7656 // FIXME: Do we care about other names here too?
7657 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7658 // We really want to find the base class destructor here.
7659 QualType T = S->Context.getTypeDeclType(BaseRecord);
7660 CanQualType CT = S->Context.getCanonicalType(T);
7661
7662 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7663 }
7664
7665 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7666 Path.Decls = Path.Decls.slice(1)) {
7667 NamedDecl *D = Path.Decls.front();
7668 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7669 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7670 return true;
7671 }
7672 }
7673
7674 return false;
7675 }
7676};
7677
7678enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7679} // end anonymous namespace
7680
7681/// Report an error regarding overriding, along with any relevant
7682/// overridden methods.
7683///
7684/// \param DiagID the primary error to report.
7685/// \param MD the overriding method.
7686/// \param OEK which overrides to include as notes.
7687static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7688 OverrideErrorKind OEK = OEK_All) {
7689 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7690 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7691 // This check (& the OEK parameter) could be replaced by a predicate, but
7692 // without lambdas that would be overkill. This is still nicer than writing
7693 // out the diag loop 3 times.
7694 if ((OEK == OEK_All) ||
7695 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7696 (OEK == OEK_Deleted && O->isDeleted()))
7697 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7698 }
7699}
7700
7701/// AddOverriddenMethods - See if a method overrides any in the base classes,
7702/// and if so, check that it's a valid override and remember it.
7703bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7704 // Look for methods in base classes that this method might override.
7705 CXXBasePaths Paths;
7706 FindOverriddenMethod FOM;
7707 FOM.Method = MD;
7708 FOM.S = this;
7709 bool hasDeletedOverridenMethods = false;
7710 bool hasNonDeletedOverridenMethods = false;
7711 bool AddedAny = false;
7712 if (DC->lookupInBases(FOM, Paths)) {
7713 for (auto *I : Paths.found_decls()) {
7714 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7715 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7716 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7717 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7718 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7719 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7720 hasDeletedOverridenMethods |= OldMD->isDeleted();
7721 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7722 AddedAny = true;
7723 }
7724 }
7725 }
7726 }
7727
7728 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7729 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7730 }
7731 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7732 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7733 }
7734
7735 return AddedAny;
7736}
7737
7738namespace {
7739 // Struct for holding all of the extra arguments needed by
7740 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7741 struct ActOnFDArgs {
7742 Scope *S;
7743 Declarator &D;
7744 MultiTemplateParamsArg TemplateParamLists;
7745 bool AddToScope;
7746 };
7747} // end anonymous namespace
7748
7749namespace {
7750
7751// Callback to only accept typo corrections that have a non-zero edit distance.
7752// Also only accept corrections that have the same parent decl.
7753class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7754 public:
7755 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7756 CXXRecordDecl *Parent)
7757 : Context(Context), OriginalFD(TypoFD),
7758 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7759
7760 bool ValidateCandidate(const TypoCorrection &candidate) override {
7761 if (candidate.getEditDistance() == 0)
7762 return false;
7763
7764 SmallVector<unsigned, 1> MismatchedParams;
7765 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7766 CDeclEnd = candidate.end();
7767 CDecl != CDeclEnd; ++CDecl) {
7768 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7769
7770 if (FD && !FD->hasBody() &&
7771 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7772 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7773 CXXRecordDecl *Parent = MD->getParent();
7774 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7775 return true;
7776 } else if (!ExpectedParent) {
7777 return true;
7778 }
7779 }
7780 }
7781
7782 return false;
7783 }
7784
7785 std::unique_ptr<CorrectionCandidateCallback> clone() override {
7786 return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7787 }
7788
7789 private:
7790 ASTContext &Context;
7791 FunctionDecl *OriginalFD;
7792 CXXRecordDecl *ExpectedParent;
7793};
7794
7795} // end anonymous namespace
7796
7797void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7798 TypoCorrectedFunctionDefinitions.insert(F);
7799}
7800
7801/// Generate diagnostics for an invalid function redeclaration.
7802///
7803/// This routine handles generating the diagnostic messages for an invalid
7804/// function redeclaration, including finding possible similar declarations
7805/// or performing typo correction if there are no previous declarations with
7806/// the same name.
7807///
7808/// Returns a NamedDecl iff typo correction was performed and substituting in
7809/// the new declaration name does not cause new errors.
7810static NamedDecl *DiagnoseInvalidRedeclaration(
7811 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7812 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7813 DeclarationName Name = NewFD->getDeclName();
7814 DeclContext *NewDC = NewFD->getDeclContext();
7815 SmallVector<unsigned, 1> MismatchedParams;
7816 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7817 TypoCorrection Correction;
7818 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7819 unsigned DiagMsg =
7820 IsLocalFriend ? diag::err_no_matching_local_friend :
7821 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7822 diag::err_member_decl_does_not_match;
7823 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7824 IsLocalFriend ? Sema::LookupLocalFriendName
7825 : Sema::LookupOrdinaryName,
7826 Sema::ForVisibleRedeclaration);
7827
7828 NewFD->setInvalidDecl();
7829 if (IsLocalFriend)
7830 SemaRef.LookupName(Prev, S);
7831 else
7832 SemaRef.LookupQualifiedName(Prev, NewDC);
7833 assert(!Prev.isAmbiguous() &&
7834 "Cannot have an ambiguity in previous-declaration lookup");
7835 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7836 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7837 MD ? MD->getParent() : nullptr);
7838 if (!Prev.empty()) {
7839 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7840 Func != FuncEnd; ++Func) {
7841 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7842 if (FD &&
7843 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7844 // Add 1 to the index so that 0 can mean the mismatch didn't
7845 // involve a parameter
7846 unsigned ParamNum =
7847 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7848 NearMatches.push_back(std::make_pair(FD, ParamNum));
7849 }
7850 }
7851 // If the qualified name lookup yielded nothing, try typo correction
7852 } else if ((Correction = SemaRef.CorrectTypo(
7853 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7854 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7855 IsLocalFriend ? nullptr : NewDC))) {
7856 // Set up everything for the call to ActOnFunctionDeclarator
7857 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7858 ExtraArgs.D.getIdentifierLoc());
7859 Previous.clear();
7860 Previous.setLookupName(Correction.getCorrection());
7861 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7862 CDeclEnd = Correction.end();
7863 CDecl != CDeclEnd; ++CDecl) {
7864 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7865 if (FD && !FD->hasBody() &&
7866 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7867 Previous.addDecl(FD);
7868 }
7869 }
7870 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7871
7872 NamedDecl *Result;
7873 // Retry building the function declaration with the new previous
7874 // declarations, and with errors suppressed.
7875 {
7876 // Trap errors.
7877 Sema::SFINAETrap Trap(SemaRef);
7878
7879 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7880 // pieces need to verify the typo-corrected C++ declaration and hopefully
7881 // eliminate the need for the parameter pack ExtraArgs.
7882 Result = SemaRef.ActOnFunctionDeclarator(
7883 ExtraArgs.S, ExtraArgs.D,
7884 Correction.getCorrectionDecl()->getDeclContext(),
7885 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7886 ExtraArgs.AddToScope);
7887
7888 if (Trap.hasErrorOccurred())
7889 Result = nullptr;
7890 }
7891
7892 if (Result) {
7893 // Determine which correction we picked.
7894 Decl *Canonical = Result->getCanonicalDecl();
7895 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7896 I != E; ++I)
7897 if ((*I)->getCanonicalDecl() == Canonical)
7898 Correction.setCorrectionDecl(*I);
7899
7900 // Let Sema know about the correction.
7901 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7902 SemaRef.diagnoseTypo(
7903 Correction,
7904 SemaRef.PDiag(IsLocalFriend
7905 ? diag::err_no_matching_local_friend_suggest
7906 : diag::err_member_decl_does_not_match_suggest)
7907 << Name << NewDC << IsDefinition);
7908 return Result;
7909 }
7910
7911 // Pretend the typo correction never occurred
7912 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7913 ExtraArgs.D.getIdentifierLoc());
7914 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7915 Previous.clear();
7916 Previous.setLookupName(Name);
7917 }
7918
7919 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7920 << Name << NewDC << IsDefinition << NewFD->getLocation();
7921
7922 bool NewFDisConst = false;
7923 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7924 NewFDisConst = NewMD->isConst();
7925
7926 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7927 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7928 NearMatch != NearMatchEnd; ++NearMatch) {
7929 FunctionDecl *FD = NearMatch->first;
7930 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7931 bool FDisConst = MD && MD->isConst();
7932 bool IsMember = MD || !IsLocalFriend;
7933
7934 // FIXME: These notes are poorly worded for the local friend case.
7935 if (unsigned Idx = NearMatch->second) {
7936 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7937 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7938 if (Loc.isInvalid()) Loc = FD->getLocation();
7939 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7940 : diag::note_local_decl_close_param_match)
7941 << Idx << FDParam->getType()
7942 << NewFD->getParamDecl(Idx - 1)->getType();
7943 } else if (FDisConst != NewFDisConst) {
7944 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7945 << NewFDisConst << FD->getSourceRange().getEnd();
7946 } else
7947 SemaRef.Diag(FD->getLocation(),
7948 IsMember ? diag::note_member_def_close_match
7949 : diag::note_local_decl_close_match);
7950 }
7951 return nullptr;
7952}
7953
7954static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7955 switch (D.getDeclSpec().getStorageClassSpec()) {
7956 default: llvm_unreachable("Unknown storage class!");
7957 case DeclSpec::SCS_auto:
7958 case DeclSpec::SCS_register:
7959 case DeclSpec::SCS_mutable:
7960 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7961 diag::err_typecheck_sclass_func);
7962 D.getMutableDeclSpec().ClearStorageClassSpecs();
7963 D.setInvalidType();
7964 break;
7965 case DeclSpec::SCS_unspecified: break;
7966 case DeclSpec::SCS_extern:
7967 if (D.getDeclSpec().isExternInLinkageSpec())
7968 return SC_None;
7969 return SC_Extern;
7970 case DeclSpec::SCS_static: {
7971 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7972 // C99 6.7.1p5:
7973 // The declaration of an identifier for a function that has
7974 // block scope shall have no explicit storage-class specifier
7975 // other than extern
7976 // See also (C++ [dcl.stc]p4).
7977 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7978 diag::err_static_block_func);
7979 break;
7980 } else
7981 return SC_Static;
7982 }
7983 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7984 }
7985
7986 // No explicit storage class has already been returned
7987 return SC_None;
7988}
7989
7990static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7991 DeclContext *DC, QualType &R,
7992 TypeSourceInfo *TInfo,
7993 StorageClass SC,
7994 bool &IsVirtualOkay) {
7995 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7996 DeclarationName Name = NameInfo.getName();
7997
7998 FunctionDecl *NewFD = nullptr;
7999 bool isInline = D.getDeclSpec().isInlineSpecified();
8000
8001 if (!SemaRef.getLangOpts().CPlusPlus) {
8002 // Determine whether the function was written with a
8003 // prototype. This true when:
8004 // - there is a prototype in the declarator, or
8005 // - the type R of the function is some kind of typedef or other non-
8006 // attributed reference to a type name (which eventually refers to a
8007 // function type).
8008 bool HasPrototype =
8009 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8010 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8011
8012 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8013 R, TInfo, SC, isInline, HasPrototype, false);
8014 if (D.isInvalidType())
8015 NewFD->setInvalidDecl();
8016
8017 return NewFD;
8018 }
8019
8020 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8021 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8022
8023 // Check that the return type is not an abstract class type.
8024 // For record types, this is done by the AbstractClassUsageDiagnoser once
8025 // the class has been completely parsed.
8026 if (!DC->isRecord() &&
8027 SemaRef.RequireNonAbstractType(
8028 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8029 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8030 D.setInvalidType();
8031
8032 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8033 // This is a C++ constructor declaration.
8034 assert(DC->isRecord() &&
8035 "Constructors can only be declared in a member context");
8036
8037 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8038 return CXXConstructorDecl::Create(
8039 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8040 TInfo, ExplicitSpecifier, isInline,
8041 /*isImplicitlyDeclared=*/false, isConstexpr);
8042
8043 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8044 // This is a C++ destructor declaration.
8045 if (DC->isRecord()) {
8046 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8047 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8048 CXXDestructorDecl *NewDD =
8049 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8050 NameInfo, R, TInfo, isInline,
8051 /*isImplicitlyDeclared=*/false);
8052
8053 // If the destructor needs an implicit exception specification, set it
8054 // now. FIXME: It'd be nice to be able to create the right type to start
8055 // with, but the type needs to reference the destructor declaration.
8056 if (SemaRef.getLangOpts().CPlusPlus11)
8057 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8058
8059 IsVirtualOkay = true;
8060 return NewDD;
8061
8062 } else {
8063 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8064 D.setInvalidType();
8065
8066 // Create a FunctionDecl to satisfy the function definition parsing
8067 // code path.
8068 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8069 D.getIdentifierLoc(), Name, R, TInfo, SC,
8070 isInline,
8071 /*hasPrototype=*/true, isConstexpr);
8072 }
8073
8074 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8075 if (!DC->isRecord()) {
8076 SemaRef.Diag(D.getIdentifierLoc(),
8077 diag::err_conv_function_not_member);
8078 return nullptr;
8079 }
8080
8081 SemaRef.CheckConversionDeclarator(D, R, SC);
8082 IsVirtualOkay = true;
8083 return CXXConversionDecl::Create(
8084 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8085 TInfo, isInline, ExplicitSpecifier, isConstexpr, SourceLocation());
8086
8087 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8088 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8089
8090 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8091 ExplicitSpecifier, NameInfo, R, TInfo,
8092 D.getEndLoc());
8093 } else if (DC->isRecord()) {
8094 // If the name of the function is the same as the name of the record,
8095 // then this must be an invalid constructor that has a return type.
8096 // (The parser checks for a return type and makes the declarator a
8097 // constructor if it has no return type).
8098 if (Name.getAsIdentifierInfo() &&
8099 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8100 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8101 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8102 << SourceRange(D.getIdentifierLoc());
8103 return nullptr;
8104 }
8105
8106 // This is a C++ method declaration.
8107 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8108 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8109 TInfo, SC, isInline, isConstexpr, SourceLocation());
8110 IsVirtualOkay = !Ret->isStatic();
8111 return Ret;
8112 } else {
8113 bool isFriend =
8114 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8115 if (!isFriend && SemaRef.CurContext->isRecord())
8116 return nullptr;
8117
8118 // Determine whether the function was written with a
8119 // prototype. This true when:
8120 // - we're in C++ (where every function has a prototype),
8121 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8122 R, TInfo, SC, isInline, true /*HasPrototype*/,
8123 isConstexpr);
8124 }
8125}
8126
8127enum OpenCLParamType {
8128 ValidKernelParam,
8129 PtrPtrKernelParam,
8130 PtrKernelParam,
8131 InvalidAddrSpacePtrKernelParam,
8132 InvalidKernelParam,
8133 RecordKernelParam
8134};
8135
8136static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8137 // Size dependent types are just typedefs to normal integer types
8138 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8139 // integers other than by their names.
8140 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8141
8142 // Remove typedefs one by one until we reach a typedef
8143 // for a size dependent type.
8144 QualType DesugaredTy = Ty;
8145 do {
8146 ArrayRef<StringRef> Names(SizeTypeNames);
8147 auto Match = llvm::find(Names, DesugaredTy.getAsString());
8148 if (Names.end() != Match)
8149 return true;
8150
8151 Ty = DesugaredTy;
8152 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8153 } while (DesugaredTy != Ty);
8154
8155 return false;
8156}
8157
8158static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8159 if (PT->isPointerType()) {
8160 QualType PointeeType = PT->getPointeeType();
8161 if (PointeeType->isPointerType())
8162 return PtrPtrKernelParam;
8163 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8164 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8165 PointeeType.getAddressSpace() == LangAS::Default)
8166 return InvalidAddrSpacePtrKernelParam;
8167 return PtrKernelParam;
8168 }
8169
8170 // OpenCL v1.2 s6.9.k:
8171 // Arguments to kernel functions in a program cannot be declared with the
8172 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8173 // uintptr_t or a struct and/or union that contain fields declared to be one
8174 // of these built-in scalar types.
8175 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8176 return InvalidKernelParam;
8177
8178 if (PT->isImageType())
8179 return PtrKernelParam;
8180
8181 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8182 return InvalidKernelParam;
8183
8184 // OpenCL extension spec v1.2 s9.5:
8185 // This extension adds support for half scalar and vector types as built-in
8186 // types that can be used for arithmetic operations, conversions etc.
8187 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8188 return InvalidKernelParam;
8189
8190 if (PT->isRecordType())
8191 return RecordKernelParam;
8192
8193 // Look into an array argument to check if it has a forbidden type.
8194 if (PT->isArrayType()) {
8195 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8196 // Call ourself to check an underlying type of an array. Since the
8197 // getPointeeOrArrayElementType returns an innermost type which is not an
8198 // array, this recursive call only happens once.
8199 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8200 }
8201
8202 return ValidKernelParam;
8203}
8204
8205static void checkIsValidOpenCLKernelParameter(
8206 Sema &S,
8207 Declarator &D,
8208 ParmVarDecl *Param,
8209 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8210 QualType PT = Param->getType();
8211
8212 // Cache the valid types we encounter to avoid rechecking structs that are
8213 // used again
8214 if (ValidTypes.count(PT.getTypePtr()))
8215 return;
8216
8217 switch (getOpenCLKernelParameterType(S, PT)) {
8218 case PtrPtrKernelParam:
8219 // OpenCL v1.2 s6.9.a:
8220 // A kernel function argument cannot be declared as a
8221 // pointer to a pointer type.
8222 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8223 D.setInvalidType();
8224 return;
8225
8226 case InvalidAddrSpacePtrKernelParam:
8227 // OpenCL v1.0 s6.5:
8228 // __kernel function arguments declared to be a pointer of a type can point
8229 // to one of the following address spaces only : __global, __local or
8230 // __constant.
8231 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8232 D.setInvalidType();
8233 return;
8234
8235 // OpenCL v1.2 s6.9.k:
8236 // Arguments to kernel functions in a program cannot be declared with the
8237 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8238 // uintptr_t or a struct and/or union that contain fields declared to be
8239 // one of these built-in scalar types.
8240
8241 case InvalidKernelParam:
8242 // OpenCL v1.2 s6.8 n:
8243 // A kernel function argument cannot be declared
8244 // of event_t type.
8245 // Do not diagnose half type since it is diagnosed as invalid argument
8246 // type for any function elsewhere.
8247 if (!PT->isHalfType()) {
8248 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8249
8250 // Explain what typedefs are involved.
8251 const TypedefType *Typedef = nullptr;
8252 while ((Typedef = PT->getAs<TypedefType>())) {
8253 SourceLocation Loc = Typedef->getDecl()->getLocation();
8254 // SourceLocation may be invalid for a built-in type.
8255 if (Loc.isValid())
8256 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8257 PT = Typedef->desugar();
8258 }
8259 }
8260
8261 D.setInvalidType();
8262 return;
8263
8264 case PtrKernelParam:
8265 case ValidKernelParam:
8266 ValidTypes.insert(PT.getTypePtr());
8267 return;
8268
8269 case RecordKernelParam:
8270 break;
8271 }
8272
8273 // Track nested structs we will inspect
8274 SmallVector<const Decl *, 4> VisitStack;
8275
8276 // Track where we are in the nested structs. Items will migrate from
8277 // VisitStack to HistoryStack as we do the DFS for bad field.
8278 SmallVector<const FieldDecl *, 4> HistoryStack;
8279 HistoryStack.push_back(nullptr);
8280
8281 // At this point we already handled everything except of a RecordType or
8282 // an ArrayType of a RecordType.
8283 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8284 const RecordType *RecTy =
8285 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8286 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8287
8288 VisitStack.push_back(RecTy->getDecl());
8289 assert(VisitStack.back() && "First decl null?");
8290
8291 do {
8292 const Decl *Next = VisitStack.pop_back_val();
8293 if (!Next) {
8294 assert(!HistoryStack.empty());
8295 // Found a marker, we have gone up a level
8296 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8297 ValidTypes.insert(Hist->getType().getTypePtr());
8298
8299 continue;
8300 }
8301
8302 // Adds everything except the original parameter declaration (which is not a
8303 // field itself) to the history stack.
8304 const RecordDecl *RD;
8305 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8306 HistoryStack.push_back(Field);
8307
8308 QualType FieldTy = Field->getType();
8309 // Other field types (known to be valid or invalid) are handled while we
8310 // walk around RecordDecl::fields().
8311 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8312 "Unexpected type.");
8313 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8314
8315 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8316 } else {
8317 RD = cast<RecordDecl>(Next);
8318 }
8319
8320 // Add a null marker so we know when we've gone back up a level
8321 VisitStack.push_back(nullptr);
8322
8323 for (const auto *FD : RD->fields()) {
8324 QualType QT = FD->getType();
8325
8326 if (ValidTypes.count(QT.getTypePtr()))
8327 continue;
8328
8329 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8330 if (ParamType == ValidKernelParam)
8331 continue;
8332
8333 if (ParamType == RecordKernelParam) {
8334 VisitStack.push_back(FD);
8335 continue;
8336 }
8337
8338 // OpenCL v1.2 s6.9.p:
8339 // Arguments to kernel functions that are declared to be a struct or union
8340 // do not allow OpenCL objects to be passed as elements of the struct or
8341 // union.
8342 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8343 ParamType == InvalidAddrSpacePtrKernelParam) {
8344 S.Diag(Param->getLocation(),
8345 diag::err_record_with_pointers_kernel_param)
8346 << PT->isUnionType()
8347 << PT;
8348 } else {
8349 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8350 }
8351
8352 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8353 << OrigRecDecl->getDeclName();
8354
8355 // We have an error, now let's go back up through history and show where
8356 // the offending field came from
8357 for (ArrayRef<const FieldDecl *>::const_iterator
8358 I = HistoryStack.begin() + 1,
8359 E = HistoryStack.end();
8360 I != E; ++I) {
8361 const FieldDecl *OuterField = *I;
8362 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8363 << OuterField->getType();
8364 }
8365
8366 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8367 << QT->isPointerType()
8368 << QT;
8369 D.setInvalidType();
8370 return;
8371 }
8372 } while (!VisitStack.empty());
8373}
8374
8375/// Find the DeclContext in which a tag is implicitly declared if we see an
8376/// elaborated type specifier in the specified context, and lookup finds
8377/// nothing.
8378static DeclContext *getTagInjectionContext(DeclContext *DC) {
8379 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8380 DC = DC->getParent();
8381 return DC;
8382}
8383
8384/// Find the Scope in which a tag is implicitly declared if we see an
8385/// elaborated type specifier in the specified context, and lookup finds
8386/// nothing.
8387static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8388 while (S->isClassScope() ||
8389 (LangOpts.CPlusPlus &&
8390 S->isFunctionPrototypeScope()) ||
8391 ((S->getFlags() & Scope::DeclScope) == 0) ||
8392 (S->getEntity() && S->getEntity()->isTransparentContext()))
8393 S = S->getParent();
8394 return S;
8395}
8396
8397NamedDecl*
8398Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8399 TypeSourceInfo *TInfo, LookupResult &Previous,
8400 MultiTemplateParamsArg TemplateParamLists,
8401 bool &AddToScope) {
8402 QualType R = TInfo->getType();
8403
8404 assert(R->isFunctionType());
8405
8406 // TODO: consider using NameInfo for diagnostic.
8407 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8408 DeclarationName Name = NameInfo.getName();
8409 StorageClass SC = getFunctionStorageClass(*this, D);
8410
8411 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8412 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8413 diag::err_invalid_thread)
8414 << DeclSpec::getSpecifierName(TSCS);
8415
8416 if (D.isFirstDeclarationOfMember())
8417 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8418 D.getIdentifierLoc());
8419
8420 bool isFriend = false;
8421 FunctionTemplateDecl *FunctionTemplate = nullptr;
8422 bool isMemberSpecialization = false;
8423 bool isFunctionTemplateSpecialization = false;
8424
8425 bool isDependentClassScopeExplicitSpecialization = false;
8426 bool HasExplicitTemplateArgs = false;
8427 TemplateArgumentListInfo TemplateArgs;
8428
8429 bool isVirtualOkay = false;
8430
8431 DeclContext *OriginalDC = DC;
8432 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8433
8434 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8435 isVirtualOkay);
8436 if (!NewFD) return nullptr;
8437
8438 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8439 NewFD->setTopLevelDeclInObjCContainer();
8440
8441 // Set the lexical context. If this is a function-scope declaration, or has a
8442 // C++ scope specifier, or is the object of a friend declaration, the lexical
8443 // context will be different from the semantic context.
8444 NewFD->setLexicalDeclContext(CurContext);
8445
8446 if (IsLocalExternDecl)
8447 NewFD->setLocalExternDecl();
8448
8449 if (getLangOpts().CPlusPlus) {
8450 bool isInline = D.getDeclSpec().isInlineSpecified();
8451 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8452 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8453 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8454 isFriend = D.getDeclSpec().isFriendSpecified();
8455 if (isFriend && !isInline && D.isFunctionDefinition()) {
8456 // C++ [class.friend]p5
8457 // A function can be defined in a friend declaration of a
8458 // class . . . . Such a function is implicitly inline.
8459 NewFD->setImplicitlyInline();
8460 }
8461
8462 // If this is a method defined in an __interface, and is not a constructor
8463 // or an overloaded operator, then set the pure flag (isVirtual will already
8464 // return true).
8465 if (const CXXRecordDecl *Parent =
8466 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8467 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8468 NewFD->setPure(true);
8469
8470 // C++ [class.union]p2
8471 // A union can have member functions, but not virtual functions.
8472 if (isVirtual && Parent->isUnion())
8473 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8474 }
8475
8476 SetNestedNameSpecifier(*this, NewFD, D);
8477 isMemberSpecialization = false;
8478 isFunctionTemplateSpecialization = false;
8479 if (D.isInvalidType())
8480 NewFD->setInvalidDecl();
8481
8482 // Match up the template parameter lists with the scope specifier, then
8483 // determine whether we have a template or a template specialization.
8484 bool Invalid = false;
8485 if (TemplateParameterList *TemplateParams =
8486 MatchTemplateParametersToScopeSpecifier(
8487 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8488 D.getCXXScopeSpec(),
8489 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8490 ? D.getName().TemplateId
8491 : nullptr,
8492 TemplateParamLists, isFriend, isMemberSpecialization,
8493 Invalid)) {
8494 if (TemplateParams->size() > 0) {
8495 // This is a function template
8496
8497 // Check that we can declare a template here.
8498 if (CheckTemplateDeclScope(S, TemplateParams))
8499 NewFD->setInvalidDecl();
8500
8501 // A destructor cannot be a template.
8502 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8503 Diag(NewFD->getLocation(), diag::err_destructor_template);
8504 NewFD->setInvalidDecl();
8505 }
8506
8507 // If we're adding a template to a dependent context, we may need to
8508 // rebuilding some of the types used within the template parameter list,
8509 // now that we know what the current instantiation is.
8510 if (DC->isDependentContext()) {
8511 ContextRAII SavedContext(*this, DC);
8512 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8513 Invalid = true;
8514 }
8515
8516 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8517 NewFD->getLocation(),
8518 Name, TemplateParams,
8519 NewFD);
8520 FunctionTemplate->setLexicalDeclContext(CurContext);
8521 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8522
8523 // For source fidelity, store the other template param lists.
8524 if (TemplateParamLists.size() > 1) {
8525 NewFD->setTemplateParameterListsInfo(Context,
8526 TemplateParamLists.drop_back(1));
8527 }
8528 } else {
8529 // This is a function template specialization.
8530 isFunctionTemplateSpecialization = true;
8531 // For source fidelity, store all the template param lists.
8532 if (TemplateParamLists.size() > 0)
8533 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8534
8535 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8536 if (isFriend) {
8537 // We want to remove the "template<>", found here.
8538 SourceRange RemoveRange = TemplateParams->getSourceRange();
8539
8540 // If we remove the template<> and the name is not a
8541 // template-id, we're actually silently creating a problem:
8542 // the friend declaration will refer to an untemplated decl,
8543 // and clearly the user wants a template specialization. So
8544 // we need to insert '<>' after the name.
8545 SourceLocation InsertLoc;
8546 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8547 InsertLoc = D.getName().getSourceRange().getEnd();
8548 InsertLoc = getLocForEndOfToken(InsertLoc);
8549 }
8550
8551 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8552 << Name << RemoveRange
8553 << FixItHint::CreateRemoval(RemoveRange)
8554 << FixItHint::CreateInsertion(InsertLoc, "<>");
8555 }
8556 }
8557 } else {
8558 // All template param lists were matched against the scope specifier:
8559 // this is NOT (an explicit specialization of) a template.
8560 if (TemplateParamLists.size() > 0)
8561 // For source fidelity, store all the template param lists.
8562 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8563 }
8564
8565 if (Invalid) {
8566 NewFD->setInvalidDecl();
8567 if (FunctionTemplate)
8568 FunctionTemplate->setInvalidDecl();
8569 }
8570
8571 // C++ [dcl.fct.spec]p5:
8572 // The virtual specifier shall only be used in declarations of
8573 // nonstatic class member functions that appear within a
8574 // member-specification of a class declaration; see 10.3.
8575 //
8576 if (isVirtual && !NewFD->isInvalidDecl()) {
8577 if (!isVirtualOkay) {
8578 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8579 diag::err_virtual_non_function);
8580 } else if (!CurContext->isRecord()) {
8581 // 'virtual' was specified outside of the class.
8582 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8583 diag::err_virtual_out_of_class)
8584 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8585 } else if (NewFD->getDescribedFunctionTemplate()) {
8586 // C++ [temp.mem]p3:
8587 // A member function template shall not be virtual.
8588 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8589 diag::err_virtual_member_function_template)
8590 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8591 } else {
8592 // Okay: Add virtual to the method.
8593 NewFD->setVirtualAsWritten(true);
8594 }
8595
8596 if (getLangOpts().CPlusPlus14 &&
8597 NewFD->getReturnType()->isUndeducedType())
8598 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8599 }
8600
8601 if (getLangOpts().CPlusPlus14 &&
8602 (NewFD->isDependentContext() ||
8603 (isFriend && CurContext->isDependentContext())) &&
8604 NewFD->getReturnType()->isUndeducedType()) {
8605 // If the function template is referenced directly (for instance, as a
8606 // member of the current instantiation), pretend it has a dependent type.
8607 // This is not really justified by the standard, but is the only sane
8608 // thing to do.
8609 // FIXME: For a friend function, we have not marked the function as being
8610 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8611 const FunctionProtoType *FPT =
8612 NewFD->getType()->castAs<FunctionProtoType>();
8613 QualType Result =
8614 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8615 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8616 FPT->getExtProtoInfo()));
8617 }
8618
8619 // C++ [dcl.fct.spec]p3:
8620 // The inline specifier shall not appear on a block scope function
8621 // declaration.
8622 if (isInline && !NewFD->isInvalidDecl()) {
8623 if (CurContext->isFunctionOrMethod()) {
8624 // 'inline' is not allowed on block scope function declaration.
8625 Diag(D.getDeclSpec().getInlineSpecLoc(),
8626 diag::err_inline_declaration_block_scope) << Name
8627 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8628 }
8629 }
8630
8631 // C++ [dcl.fct.spec]p6:
8632 // The explicit specifier shall be used only in the declaration of a
8633 // constructor or conversion function within its class definition;
8634 // see 12.3.1 and 12.3.2.
8635 if (hasExplicit && !NewFD->isInvalidDecl() &&
8636 !isa<CXXDeductionGuideDecl>(NewFD)) {
8637 if (!CurContext->isRecord()) {
8638 // 'explicit' was specified outside of the class.
8639 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8640 diag::err_explicit_out_of_class)
8641 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8642 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8643 !isa<CXXConversionDecl>(NewFD)) {
8644 // 'explicit' was specified on a function that wasn't a constructor
8645 // or conversion function.
8646 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8647 diag::err_explicit_non_ctor_or_conv_function)
8648 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8649 }
8650 }
8651
8652 if (isConstexpr) {
8653 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8654 // are implicitly inline.
8655 NewFD->setImplicitlyInline();
8656
8657 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8658 // be either constructors or to return a literal type. Therefore,
8659 // destructors cannot be declared constexpr.
8660 if (isa<CXXDestructorDecl>(NewFD))
8661 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8662 }
8663
8664 // If __module_private__ was specified, mark the function accordingly.
8665 if (D.getDeclSpec().isModulePrivateSpecified()) {
8666 if (isFunctionTemplateSpecialization) {
8667 SourceLocation ModulePrivateLoc
8668 = D.getDeclSpec().getModulePrivateSpecLoc();
8669 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8670 << 0
8671 << FixItHint::CreateRemoval(ModulePrivateLoc);
8672 } else {
8673 NewFD->setModulePrivate();
8674 if (FunctionTemplate)
8675 FunctionTemplate->setModulePrivate();
8676 }
8677 }
8678
8679 if (isFriend) {
8680 if (FunctionTemplate) {
8681 FunctionTemplate->setObjectOfFriendDecl();
8682 FunctionTemplate->setAccess(AS_public);
8683 }
8684 NewFD->setObjectOfFriendDecl();
8685 NewFD->setAccess(AS_public);
8686 }
8687
8688 // If a function is defined as defaulted or deleted, mark it as such now.
8689 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8690 // definition kind to FDK_Definition.
8691 switch (D.getFunctionDefinitionKind()) {
8692 case FDK_Declaration:
8693 case FDK_Definition:
8694 break;
8695
8696 case FDK_Defaulted:
8697 NewFD->setDefaulted();
8698 break;
8699
8700 case FDK_Deleted:
8701 NewFD->setDeletedAsWritten();
8702 break;
8703 }
8704
8705 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8706 D.isFunctionDefinition()) {
8707 // C++ [class.mfct]p2:
8708 // A member function may be defined (8.4) in its class definition, in
8709 // which case it is an inline member function (7.1.2)
8710 NewFD->setImplicitlyInline();
8711 }
8712
8713 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8714 !CurContext->isRecord()) {
8715 // C++ [class.static]p1:
8716 // A data or function member of a class may be declared static
8717 // in a class definition, in which case it is a static member of
8718 // the class.
8719
8720 // Complain about the 'static' specifier if it's on an out-of-line
8721 // member function definition.
8722
8723 // MSVC permits the use of a 'static' storage specifier on an out-of-line
8724 // member function template declaration and class member template
8725 // declaration (MSVC versions before 2015), warn about this.
8726 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8727 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8728 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8729 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8730 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8731 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8732 }
8733
8734 // C++11 [except.spec]p15:
8735 // A deallocation function with no exception-specification is treated
8736 // as if it were specified with noexcept(true).
8737 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8738 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8739 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8740 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8741 NewFD->setType(Context.getFunctionType(
8742 FPT->getReturnType(), FPT->getParamTypes(),
8743 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8744 }
8745
8746 // Filter out previous declarations that don't match the scope.
8747 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8748 D.getCXXScopeSpec().isNotEmpty() ||
8749 isMemberSpecialization ||
8750 isFunctionTemplateSpecialization);
8751
8752 // Handle GNU asm-label extension (encoded as an attribute).
8753 if (Expr *E = (Expr*) D.getAsmLabel()) {
8754 // The parser guarantees this is a string.
8755 StringLiteral *SE = cast<StringLiteral>(E);
8756 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8757 SE->getString(), 0));
8758 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8759 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8760 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8761 if (I != ExtnameUndeclaredIdentifiers.end()) {
8762 if (isDeclExternC(NewFD)) {
8763 NewFD->addAttr(I->second);
8764 ExtnameUndeclaredIdentifiers.erase(I);
8765 } else
8766 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8767 << /*Variable*/0 << NewFD;
8768 }
8769 }
8770
8771 // Copy the parameter declarations from the declarator D to the function
8772 // declaration NewFD, if they are available. First scavenge them into Params.
8773 SmallVector<ParmVarDecl*, 16> Params;
8774 unsigned FTIIdx;
8775 if (D.isFunctionDeclarator(FTIIdx)) {
8776 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8777
8778 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8779 // function that takes no arguments, not a function that takes a
8780 // single void argument.
8781 // We let through "const void" here because Sema::GetTypeForDeclarator
8782 // already checks for that case.
8783 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8784 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8785 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8786 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8787 Param->setDeclContext(NewFD);
8788 Params.push_back(Param);
8789
8790 if (Param->isInvalidDecl())
8791 NewFD->setInvalidDecl();
8792 }
8793 }
8794
8795 if (!getLangOpts().CPlusPlus) {
8796 // In C, find all the tag declarations from the prototype and move them
8797 // into the function DeclContext. Remove them from the surrounding tag
8798 // injection context of the function, which is typically but not always
8799 // the TU.
8800 DeclContext *PrototypeTagContext =
8801 getTagInjectionContext(NewFD->getLexicalDeclContext());
8802 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8803 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8804
8805 // We don't want to reparent enumerators. Look at their parent enum
8806 // instead.
8807 if (!TD) {
8808 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8809 TD = cast<EnumDecl>(ECD->getDeclContext());
8810 }
8811 if (!TD)
8812 continue;
8813 DeclContext *TagDC = TD->getLexicalDeclContext();
8814 if (!TagDC->containsDecl(TD))
8815 continue;
8816 TagDC->removeDecl(TD);
8817 TD->setDeclContext(NewFD);
8818 NewFD->addDecl(TD);
8819
8820 // Preserve the lexical DeclContext if it is not the surrounding tag
8821 // injection context of the FD. In this example, the semantic context of
8822 // E will be f and the lexical context will be S, while both the
8823 // semantic and lexical contexts of S will be f:
8824 // void f(struct S { enum E { a } f; } s);
8825 if (TagDC != PrototypeTagContext)
8826 TD->setLexicalDeclContext(TagDC);
8827 }
8828 }
8829 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8830 // When we're declaring a function with a typedef, typeof, etc as in the
8831 // following example, we'll need to synthesize (unnamed)
8832 // parameters for use in the declaration.
8833 //
8834 // @code
8835 // typedef void fn(int);
8836 // fn f;
8837 // @endcode
8838
8839 // Synthesize a parameter for each argument type.
8840 for (const auto &AI : FT->param_types()) {
8841 ParmVarDecl *Param =
8842 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8843 Param->setScopeInfo(0, Params.size());
8844 Params.push_back(Param);
8845 }
8846 } else {
8847 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8848 "Should not need args for typedef of non-prototype fn");
8849 }
8850
8851 // Finally, we know we have the right number of parameters, install them.
8852 NewFD->setParams(Params);
8853
8854 if (D.getDeclSpec().isNoreturnSpecified())
8855 NewFD->addAttr(
8856 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8857 Context, 0));
8858
8859 // Functions returning a variably modified type violate C99 6.7.5.2p2
8860 // because all functions have linkage.
8861 if (!NewFD->isInvalidDecl() &&
8862 NewFD->getReturnType()->isVariablyModifiedType()) {
8863 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8864 NewFD->setInvalidDecl();
8865 }
8866
8867 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8868 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8869 !NewFD->hasAttr<SectionAttr>()) {
8870 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8871 PragmaClangTextSection.SectionName,
8872 PragmaClangTextSection.PragmaLocation));
8873 }
8874
8875 // Apply an implicit SectionAttr if #pragma code_seg is active.
8876 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8877 !NewFD->hasAttr<SectionAttr>()) {
8878 NewFD->addAttr(
8879 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8880 CodeSegStack.CurrentValue->getString(),
8881 CodeSegStack.CurrentPragmaLocation));
8882 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8883 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8884 ASTContext::PSF_Read,
8885 NewFD))
8886 NewFD->dropAttr<SectionAttr>();
8887 }
8888
8889 // Apply an implicit CodeSegAttr from class declspec or
8890 // apply an implicit SectionAttr from #pragma code_seg if active.
8891 if (!NewFD->hasAttr<CodeSegAttr>()) {
8892 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8893 D.isFunctionDefinition())) {
8894 NewFD->addAttr(SAttr);
8895 }
8896 }
8897
8898 // Handle attributes.
8899 ProcessDeclAttributes(S, NewFD, D);
8900
8901 if (NewFD->hasAttr<PointerInterpretationCapsAttr>()) {
8902 // FIXME: This will assert on failure - it should print a nice error.
8903 //unsigned CapAS = Context.getTargetInfo() .AddressSpaceForCapabilities();
8904 const FunctionProtoType *FPT =
8905 NewFD->getType()->getAs<FunctionProtoType>();
8906 ArrayRef<QualType> OldParams = FPT->getParamTypes();
8907 llvm::SmallVector<QualType, 8> NewParams;
8908 for (QualType T : OldParams) {
8909 if (const PointerType *PT = T->getAs<PointerType>())
8910 NewParams.push_back(Context.getPointerType(PT->getPointeeType(),
8911 ASTContext::PIK_Capability));
8912 else
8913 NewParams.push_back(T);
8914 }
8915 QualType RetTy = FPT->getReturnType();
8916 if (const PointerType *PT = RetTy->getAs<PointerType>())
8917 RetTy = Context.getPointerType(PT->getPointeeType(),
8918 ASTContext::PIK_Capability);
8919 NewFD->setType(Context.getFunctionType(RetTy, NewParams,
8920 FPT->getExtProtoInfo()));
8921 }
8922
8923 QualType RetType = NewFD->getReturnType();
8924
8925 if (CHERIMethodSuffixAttr *Attr = NewFD->getAttr<CHERIMethodSuffixAttr>()) {
8926 auto *TU = Context.getTranslationUnitDecl();
8927 // Lookup the type of cheri_object, or generate it if it isn't specified.
8928 QualType CHERIClassTy;
8929 IdentifierInfo &ClassII = Context.Idents.get("cheri_object");
8930 DeclarationName ClassDN(&ClassII);
8931 auto Defs = TU->lookup(ClassDN);
8932 for (NamedDecl *D : Defs)
8933 if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
8934 CHERIClassTy = Context.getTypeDeclType(RD);
8935 if (CHERIClassTy == QualType())
8936 CHERIClassTy = Context.getCHERIClassType();
8937 // Construct a new function prototype that is the same as the original,
8938 // except that it has an extra struct cheri_object as the first argument.
8939 const FunctionProtoType *OFT =
8940 NewFD->getType()->getAs<FunctionProtoType>();
8941 const ArrayRef<QualType> Params = OFT->getParamTypes();
8942 SmallVector<QualType, 16> NewParams;
8943 NewParams.push_back(CHERIClassTy);
8944 NewParams.insert(NewParams.end(), Params.begin(), Params.end());
8945 FunctionProtoType::ExtProtoInfo EPI = OFT->getExtProtoInfo();
8946 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_CHERICCall);
8947 QualType WrappedType = Context.getFunctionType(RetType, NewParams, EPI);
8948 // Construct the new function name, taking the old one and adding the
8949 // suffix.
8950 std::string Name = (NewFD->getName() + Attr->getSuffix()).str();
8951 IdentifierInfo &II = Context.Idents.get(Name);
8952 DeclarationName DN(&II);
8953 DeclarationNameInfo DNI(DN, SourceLocation());
8954 // construct the function decl and its associated parameter decls
8955 FunctionDecl *WrappedFD = FunctionDecl::Create(Context,
8956 NewFD->getDeclContext(), NewFD->getTypeSpecStartLoc(), DNI,
8957 WrappedType, TInfo, SC_Extern, false, true);
8958 SmallVector<ParmVarDecl*, 16> Parms;
8959 for (QualType Ty : NewParams) {
8960 Parms.push_back(ParmVarDecl::Create(Context, NewFD, SourceLocation(),
8961 SourceLocation(), nullptr, Ty, Context.getTrivialTypeSourceInfo(Ty,
8962 SourceLocation()), SC_None, nullptr));
8963 }
8964 WrappedFD->setParams(Parms);
8965 // Propagate the default class (the calling convention is copied
8966 // automatically). This won't be used in the suffixed version, but is used
8967 // to look up the method number.
8968 if (CHERIMethodClassAttr *Cls = NewFD->getAttr<CHERIMethodClassAttr>())
8969 WrappedFD->addAttr(Cls->clone(Context));
8970 WrappedFD->addAttr(Attr->clone(Context));
8971 Attr->setSuffix(Context, "");
8972 // Make the new prototype visible.
8973 NewFD->getLexicalDeclContext()->addDecl(WrappedFD);
8974 S->AddDecl(WrappedFD);
8975 IdResolver.AddDecl(WrappedFD);
8976 }
8977
8978 if (getLangOpts().OpenCL) {
8979 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8980 // type declaration will generate a compilation error.
8981 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8982 if (AddressSpace != LangAS::Default) {
8983 Diag(NewFD->getLocation(),
8984 diag::err_opencl_return_value_with_address_space);
8985 NewFD->setInvalidDecl();
8986 }
8987 }
8988
8989 if (!getLangOpts().CPlusPlus) {
8990 // Perform semantic checking on the function declaration.
8991 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8992 CheckMain(NewFD, D.getDeclSpec());
8993
8994 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8995 CheckMSVCRTEntryPoint(NewFD);
8996
8997 if (!NewFD->isInvalidDecl())
8998 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8999 isMemberSpecialization));
9000 else if (!Previous.empty())
9001 // Recover gracefully from an invalid redeclaration.
9002 D.setRedeclaration(true);
9003 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9004 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9005 "previous declaration set still overloaded");
9006
9007 // Diagnose no-prototype function declarations with calling conventions that
9008 // don't support variadic calls. Only do this in C and do it after merging
9009 // possibly prototyped redeclarations.
9010 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9011 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9012 CallingConv CC = FT->getExtInfo().getCC();
9013 if (!supportsVariadicCall(CC)) {
9014 // Windows system headers sometimes accidentally use stdcall without
9015 // (void) parameters, so we relax this to a warning.
9016 int DiagID =
9017 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9018 Diag(NewFD->getLocation(), DiagID)
9019 << FunctionType::getNameForCallConv(CC);
9020 }
9021 }
9022 } else {
9023 // C++11 [replacement.functions]p3:
9024 // The program's definitions shall not be specified as inline.
9025 //
9026 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9027 //
9028 // Suppress the diagnostic if the function is __attribute__((used)), since
9029 // that forces an external definition to be emitted.
9030 if (D.getDeclSpec().isInlineSpecified() &&
9031 NewFD->isReplaceableGlobalAllocationFunction() &&
9032 !NewFD->hasAttr<UsedAttr>())
9033 Diag(D.getDeclSpec().getInlineSpecLoc(),
9034 diag::ext_operator_new_delete_declared_inline)
9035 << NewFD->getDeclName();
9036
9037 // If the declarator is a template-id, translate the parser's template
9038 // argument list into our AST format.
9039 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9040 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9041 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9042 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9043 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9044 TemplateId->NumArgs);
9045 translateTemplateArguments(TemplateArgsPtr,
9046 TemplateArgs);
9047
9048 HasExplicitTemplateArgs = true;
9049
9050 if (NewFD->isInvalidDecl()) {
9051 HasExplicitTemplateArgs = false;
9052 } else if (FunctionTemplate) {
9053 // Function template with explicit template arguments.
9054 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9055 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9056
9057 HasExplicitTemplateArgs = false;
9058 } else {
9059 assert((isFunctionTemplateSpecialization ||
9060 D.getDeclSpec().isFriendSpecified()) &&
9061 "should have a 'template<>' for this decl");
9062 // "friend void foo<>(int);" is an implicit specialization decl.
9063 isFunctionTemplateSpecialization = true;
9064 }
9065 } else if (isFriend && isFunctionTemplateSpecialization) {
9066 // This combination is only possible in a recovery case; the user
9067 // wrote something like:
9068 // template <> friend void foo(int);
9069 // which we're recovering from as if the user had written:
9070 // friend void foo<>(int);
9071 // Go ahead and fake up a template id.
9072 HasExplicitTemplateArgs = true;
9073 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9074 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9075 }
9076
9077 // We do not add HD attributes to specializations here because
9078 // they may have different constexpr-ness compared to their
9079 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9080 // may end up with different effective targets. Instead, a
9081 // specialization inherits its target attributes from its template
9082 // in the CheckFunctionTemplateSpecialization() call below.
9083 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
9084 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9085
9086 // If it's a friend (and only if it's a friend), it's possible
9087 // that either the specialized function type or the specialized
9088 // template is dependent, and therefore matching will fail. In
9089 // this case, don't check the specialization yet.
9090 bool InstantiationDependent = false;
9091 if (isFunctionTemplateSpecialization && isFriend &&
9092 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9093 TemplateSpecializationType::anyDependentTemplateArguments(
9094 TemplateArgs,
9095 InstantiationDependent))) {
9096 assert(HasExplicitTemplateArgs &&
9097 "friend function specialization without template args");
9098 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9099 Previous))
9100 NewFD->setInvalidDecl();
9101 } else if (isFunctionTemplateSpecialization) {
9102 if (CurContext->isDependentContext() && CurContext->isRecord()
9103 && !isFriend) {
9104 isDependentClassScopeExplicitSpecialization = true;
9105 } else if (!NewFD->isInvalidDecl() &&
9106 CheckFunctionTemplateSpecialization(
9107 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9108 Previous))
9109 NewFD->setInvalidDecl();
9110
9111 // C++ [dcl.stc]p1:
9112 // A storage-class-specifier shall not be specified in an explicit
9113 // specialization (14.7.3)
9114 FunctionTemplateSpecializationInfo *Info =
9115 NewFD->getTemplateSpecializationInfo();
9116 if (Info && SC != SC_None) {
9117 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9118 Diag(NewFD->getLocation(),
9119 diag::err_explicit_specialization_inconsistent_storage_class)
9120 << SC
9121 << FixItHint::CreateRemoval(
9122 D.getDeclSpec().getStorageClassSpecLoc());
9123
9124 else
9125 Diag(NewFD->getLocation(),
9126 diag::ext_explicit_specialization_storage_class)
9127 << FixItHint::CreateRemoval(
9128 D.getDeclSpec().getStorageClassSpecLoc());
9129 }
9130 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9131 if (CheckMemberSpecialization(NewFD, Previous))
9132 NewFD->setInvalidDecl();
9133 }
9134
9135 // Perform semantic checking on the function declaration.
9136 if (!isDependentClassScopeExplicitSpecialization) {
9137 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9138 CheckMain(NewFD, D.getDeclSpec());
9139
9140 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9141 CheckMSVCRTEntryPoint(NewFD);
9142
9143 if (!NewFD->isInvalidDecl())
9144 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9145 isMemberSpecialization));
9146 else if (!Previous.empty())
9147 // Recover gracefully from an invalid redeclaration.
9148 D.setRedeclaration(true);
9149 }
9150
9151 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9152 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9153 "previous declaration set still overloaded");
9154
9155 NamedDecl *PrincipalDecl = (FunctionTemplate
9156 ? cast<NamedDecl>(FunctionTemplate)
9157 : NewFD);
9158
9159 if (isFriend && NewFD->getPreviousDecl()) {
9160 AccessSpecifier Access = AS_public;
9161 if (!NewFD->isInvalidDecl())
9162 Access = NewFD->getPreviousDecl()->getAccess();
9163
9164 NewFD->setAccess(Access);
9165 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9166 }
9167
9168 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9169 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9170 PrincipalDecl->setNonMemberOperator();
9171
9172 // If we have a function template, check the template parameter
9173 // list. This will check and merge default template arguments.
9174 if (FunctionTemplate) {
9175 FunctionTemplateDecl *PrevTemplate =
9176 FunctionTemplate->getPreviousDecl();
9177 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9178 PrevTemplate ? PrevTemplate->getTemplateParameters()
9179 : nullptr,
9180 D.getDeclSpec().isFriendSpecified()
9181 ? (D.isFunctionDefinition()
9182 ? TPC_FriendFunctionTemplateDefinition
9183 : TPC_FriendFunctionTemplate)
9184 : (D.getCXXScopeSpec().isSet() &&
9185 DC && DC->isRecord() &&
9186 DC->isDependentContext())
9187 ? TPC_ClassTemplateMember
9188 : TPC_FunctionTemplate);
9189 }
9190
9191 if (NewFD->isInvalidDecl()) {
9192 // Ignore all the rest of this.
9193 } else if (!D.isRedeclaration()) {
9194 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9195 AddToScope };
9196 // Fake up an access specifier if it's supposed to be a class member.
9197 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9198 NewFD->setAccess(AS_public);
9199
9200 // Qualified decls generally require a previous declaration.
9201 if (D.getCXXScopeSpec().isSet()) {
9202 // ...with the major exception of templated-scope or
9203 // dependent-scope friend declarations.
9204
9205 // TODO: we currently also suppress this check in dependent
9206 // contexts because (1) the parameter depth will be off when
9207 // matching friend templates and (2) we might actually be
9208 // selecting a friend based on a dependent factor. But there
9209 // are situations where these conditions don't apply and we
9210 // can actually do this check immediately.
9211 //
9212 // Unless the scope is dependent, it's always an error if qualified
9213 // redeclaration lookup found nothing at all. Diagnose that now;
9214 // nothing will diagnose that error later.
9215 if (isFriend &&
9216 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9217 (!Previous.empty() && CurContext->isDependentContext()))) {
9218 // ignore these
9219 } else {
9220 // The user tried to provide an out-of-line definition for a
9221 // function that is a member of a class or namespace, but there
9222 // was no such member function declared (C++ [class.mfct]p2,
9223 // C++ [namespace.memdef]p2). For example:
9224 //
9225 // class X {
9226 // void f() const;
9227 // };
9228 //
9229 // void X::f() { } // ill-formed
9230 //
9231 // Complain about this problem, and attempt to suggest close
9232 // matches (e.g., those that differ only in cv-qualifiers and
9233 // whether the parameter types are references).
9234
9235 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9236 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9237 AddToScope = ExtraArgs.AddToScope;
9238 return Result;
9239 }
9240 }
9241
9242 // Unqualified local friend declarations are required to resolve
9243 // to something.
9244 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9245 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9246 *this, Previous, NewFD, ExtraArgs, true, S)) {
9247 AddToScope = ExtraArgs.AddToScope;
9248 return Result;
9249 }
9250 }
9251 } else if (!D.isFunctionDefinition() &&
9252 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9253 !isFriend && !isFunctionTemplateSpecialization &&
9254 !isMemberSpecialization) {
9255 // An out-of-line member function declaration must also be a
9256 // definition (C++ [class.mfct]p2).
9257 // Note that this is not the case for explicit specializations of
9258 // function templates or member functions of class templates, per
9259 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9260 // extension for compatibility with old SWIG code which likes to
9261 // generate them.
9262 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9263 << D.getCXXScopeSpec().getRange();
9264 }
9265 }
9266
9267 ProcessPragmaWeak(S, NewFD);
9268 checkAttributesAfterMerging(*this, *NewFD);
9269
9270 AddKnownFunctionAttributes(NewFD);
9271
9272 if (NewFD->hasAttr<OverloadableAttr>() &&
9273 !NewFD->getType()->getAs<FunctionProtoType>()) {
9274 Diag(NewFD->getLocation(),
9275 diag::err_attribute_overloadable_no_prototype)
9276 << NewFD;
9277
9278 // Turn this into a variadic function with no parameters.
9279 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9280 FunctionProtoType::ExtProtoInfo EPI(
9281 Context.getDefaultCallingConvention(true, false));
9282 EPI.Variadic = true;
9283 EPI.ExtInfo = FT->getExtInfo();
9284
9285 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9286 NewFD->setType(R);
9287 }
9288
9289 // If there's a #pragma GCC visibility in scope, and this isn't a class
9290 // member, set the visibility of this function.
9291 if (!DC->isRecord() && NewFD->isExternallyVisible())
9292 AddPushedVisibilityAttribute(NewFD);
9293
9294 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9295 // marking the function.
9296 AddCFAuditedAttribute(NewFD);
9297
9298 // If this is a function definition, check if we have to apply optnone due to
9299 // a pragma.
9300 if(D.isFunctionDefinition())
9301 AddRangeBasedOptnone(NewFD);
9302
9303 // If this is the first declaration of an extern C variable, update
9304 // the map of such variables.
9305 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9306 isIncompleteDeclExternC(*this, NewFD))
9307 RegisterLocallyScopedExternCDecl(NewFD, S);
9308
9309 // Set this FunctionDecl's range up to the right paren.
9310 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9311
9312 if (D.isRedeclaration() && !Previous.empty()) {
9313 NamedDecl *Prev = Previous.getRepresentativeDecl();
9314 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9315 isMemberSpecialization ||
9316 isFunctionTemplateSpecialization,
9317 D.isFunctionDefinition());
9318 }
9319
9320 if (getLangOpts().CUDA) {
9321 IdentifierInfo *II = NewFD->getIdentifier();
9322 if (II && II->isStr(getCudaConfigureFuncName()) &&
9323 !NewFD->isInvalidDecl() &&
9324 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9325 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9326 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9327 << getCudaConfigureFuncName();
9328 Context.setcudaConfigureCallDecl(NewFD);
9329 }
9330
9331 // Variadic functions, other than a *declaration* of printf, are not allowed
9332 // in device-side CUDA code, unless someone passed
9333 // -fcuda-allow-variadic-functions.
9334 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9335 (NewFD->hasAttr<CUDADeviceAttr>() ||
9336 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9337 !(II && II->isStr("printf") && NewFD->isExternC() &&
9338 !D.isFunctionDefinition())) {
9339 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9340 }
9341 }
9342
9343 MarkUnusedFileScopedDecl(NewFD);
9344
9345
9346
9347 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9348 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9349 if ((getLangOpts().OpenCLVersion >= 120)
9350 && (SC == SC_Static)) {
9351 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9352 D.setInvalidType();
9353 }
9354
9355 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9356 if (!NewFD->getReturnType()->isVoidType()) {
9357 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9358 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9359 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9360 : FixItHint());
9361 D.setInvalidType();
9362 }
9363
9364 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9365 for (auto Param : NewFD->parameters())
9366 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9367
9368 if (getLangOpts().OpenCLCPlusPlus) {
9369 if (DC->isRecord()) {
9370 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9371 D.setInvalidType();
9372 }
9373 if (FunctionTemplate) {
9374 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9375 D.setInvalidType();
9376 }
9377 }
9378 }
9379
9380 if (getLangOpts().CPlusPlus) {
9381 if (FunctionTemplate) {
9382 if (NewFD->isInvalidDecl())
9383 FunctionTemplate->setInvalidDecl();
9384 return FunctionTemplate;
9385 }
9386
9387 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9388 CompleteMemberSpecialization(NewFD, Previous);
9389 }
9390
9391 for (const ParmVarDecl *Param : NewFD->parameters()) {
9392 QualType PT = Param->getType();
9393
9394 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9395 // types.
9396 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9397 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9398 QualType ElemTy = PipeTy->getElementType();
9399 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9400 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9401 D.setInvalidType();
9402 }
9403 }
9404 }
9405 }
9406
9407 // Here we have an function template explicit specialization at class scope.
9408 // The actual specialization will be postponed to template instatiation
9409 // time via the ClassScopeFunctionSpecializationDecl node.
9410 if (isDependentClassScopeExplicitSpecialization) {
9411 ClassScopeFunctionSpecializationDecl *NewSpec =
9412 ClassScopeFunctionSpecializationDecl::Create(
9413 Context, CurContext, NewFD->getLocation(),
9414 cast<CXXMethodDecl>(NewFD),
9415 HasExplicitTemplateArgs, TemplateArgs);
9416 CurContext->addDecl(NewSpec);
9417 AddToScope = false;
9418 }
9419
9420 // Diagnose availability attributes. Availability cannot be used on functions
9421 // that are run during load/unload.
9422 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9423 if (NewFD->hasAttr<ConstructorAttr>()) {
9424 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9425 << 1;
9426 NewFD->dropAttr<AvailabilityAttr>();
9427 }
9428 if (NewFD->hasAttr<DestructorAttr>()) {
9429 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9430 << 2;
9431 NewFD->dropAttr<AvailabilityAttr>();
9432 }
9433 }
9434
9435 return NewFD;
9436}
9437
9438/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9439/// when __declspec(code_seg) "is applied to a class, all member functions of
9440/// the class and nested classes -- this includes compiler-generated special
9441/// member functions -- are put in the specified segment."
9442/// The actual behavior is a little more complicated. The Microsoft compiler
9443/// won't check outer classes if there is an active value from #pragma code_seg.
9444/// The CodeSeg is always applied from the direct parent but only from outer
9445/// classes when the #pragma code_seg stack is empty. See:
9446/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9447/// available since MS has removed the page.
9448static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9449 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9450 if (!Method)
9451 return nullptr;
9452 const CXXRecordDecl *Parent = Method->getParent();
9453 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9454 Attr *NewAttr = SAttr->clone(S.getASTContext());
9455 NewAttr->setImplicit(true);
9456 return NewAttr;
9457 }
9458
9459 // The Microsoft compiler won't check outer classes for the CodeSeg
9460 // when the #pragma code_seg stack is active.
9461 if (S.CodeSegStack.CurrentValue)
9462 return nullptr;
9463
9464 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9465 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9466 Attr *NewAttr = SAttr->clone(S.getASTContext());
9467 NewAttr->setImplicit(true);
9468 return NewAttr;
9469 }
9470 }
9471 return nullptr;
9472}
9473
9474/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9475/// containing class. Otherwise it will return implicit SectionAttr if the
9476/// function is a definition and there is an active value on CodeSegStack
9477/// (from the current #pragma code-seg value).
9478///
9479/// \param FD Function being declared.
9480/// \param IsDefinition Whether it is a definition or just a declarartion.
9481/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9482/// nullptr if no attribute should be added.
9483Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9484 bool IsDefinition) {
9485 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9486 return A;
9487 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9488 CodeSegStack.CurrentValue) {
9489 return SectionAttr::CreateImplicit(getASTContext(),
9490 SectionAttr::Declspec_allocate,
9491 CodeSegStack.CurrentValue->getString(),
9492 CodeSegStack.CurrentPragmaLocation);
9493 }
9494 return nullptr;
9495}
9496
9497/// Determines if we can perform a correct type check for \p D as a
9498/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9499/// best-effort check.
9500///
9501/// \param NewD The new declaration.
9502/// \param OldD The old declaration.
9503/// \param NewT The portion of the type of the new declaration to check.
9504/// \param OldT The portion of the type of the old declaration to check.
9505bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9506 QualType NewT, QualType OldT) {
9507 if (!NewD->getLexicalDeclContext()->isDependentContext())
9508 return true;
9509
9510 // For dependently-typed local extern declarations and friends, we can't
9511 // perform a correct type check in general until instantiation:
9512 //
9513 // int f();
9514 // template<typename T> void g() { T f(); }
9515 //
9516 // (valid if g() is only instantiated with T = int).
9517 if (NewT->isDependentType() &&
9518 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9519 return false;
9520
9521 // Similarly, if the previous declaration was a dependent local extern
9522 // declaration, we don't really know its type yet.
9523 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9524 return false;
9525
9526 return true;
9527}
9528
9529/// Checks if the new declaration declared in dependent context must be
9530/// put in the same redeclaration chain as the specified declaration.
9531///
9532/// \param D Declaration that is checked.
9533/// \param PrevDecl Previous declaration found with proper lookup method for the
9534/// same declaration name.
9535/// \returns True if D must be added to the redeclaration chain which PrevDecl
9536/// belongs to.
9537///
9538bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9539 if (!D->getLexicalDeclContext()->isDependentContext())
9540 return true;
9541
9542 // Don't chain dependent friend function definitions until instantiation, to
9543 // permit cases like
9544 //
9545 // void func();
9546 // template<typename T> class C1 { friend void func() {} };
9547 // template<typename T> class C2 { friend void func() {} };
9548 //
9549 // ... which is valid if only one of C1 and C2 is ever instantiated.
9550 //
9551 // FIXME: This need only apply to function definitions. For now, we proxy
9552 // this by checking for a file-scope function. We do not want this to apply
9553 // to friend declarations nominating member functions, because that gets in
9554 // the way of access checks.
9555 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9556 return false;
9557
9558 auto *VD = dyn_cast<ValueDecl>(D);
9559 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9560 return !VD || !PrevVD ||
9561 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9562 PrevVD->getType());
9563}
9564
9565/// Check the target attribute of the function for MultiVersion
9566/// validity.
9567///
9568/// Returns true if there was an error, false otherwise.
9569static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9570 const auto *TA = FD->getAttr<TargetAttr>();
9571 assert(TA && "MultiVersion Candidate requires a target attribute");
9572 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9573 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9574 enum ErrType { Feature = 0, Architecture = 1 };
9575
9576 if (!ParseInfo.Architecture.empty() &&
9577 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9578 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9579 << Architecture << ParseInfo.Architecture;
9580 return true;
9581 }
9582
9583 for (const auto &Feat : ParseInfo.Features) {
9584 auto BareFeat = StringRef{Feat}.substr(1);
9585 if (Feat[0] == '-') {
9586 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9587 << Feature << ("no-" + BareFeat).str();
9588 return true;
9589 }
9590
9591 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9592 !TargetInfo.isValidFeatureName(BareFeat)) {
9593 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9594 << Feature << BareFeat;
9595 return true;
9596 }
9597 }
9598 return false;
9599}
9600
9601static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9602 MultiVersionKind MVType) {
9603 for (const Attr *A : FD->attrs()) {
9604 switch (A->getKind()) {
9605 case attr::CPUDispatch:
9606 case attr::CPUSpecific:
9607 if (MVType != MultiVersionKind::CPUDispatch &&
9608 MVType != MultiVersionKind::CPUSpecific)
9609 return true;
9610 break;
9611 case attr::Target:
9612 if (MVType != MultiVersionKind::Target)
9613 return true;
9614 break;
9615 default:
9616 return true;
9617 }
9618 }
9619 return false;
9620}
9621
9622static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9623 const FunctionDecl *NewFD,
9624 bool CausesMV,
9625 MultiVersionKind MVType) {
9626 enum DoesntSupport {
9627 FuncTemplates = 0,
9628 VirtFuncs = 1,
9629 DeducedReturn = 2,
9630 Constructors = 3,
9631 Destructors = 4,
9632 DeletedFuncs = 5,
9633 DefaultedFuncs = 6,
9634 ConstexprFuncs = 7,
9635 };
9636 enum Different {
9637 CallingConv = 0,
9638 ReturnType = 1,
9639 ConstexprSpec = 2,
9640 InlineSpec = 3,
9641 StorageClass = 4,
9642 Linkage = 5
9643 };
9644
9645 bool IsCPUSpecificCPUDispatchMVType =
9646 MVType == MultiVersionKind::CPUDispatch ||
9647 MVType == MultiVersionKind::CPUSpecific;
9648
9649 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9650 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9651 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9652 return true;
9653 }
9654
9655 if (!NewFD->getType()->getAs<FunctionProtoType>())
9656 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9657
9658 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9659 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9660 if (OldFD)
9661 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9662 return true;
9663 }
9664
9665 // For now, disallow all other attributes. These should be opt-in, but
9666 // an analysis of all of them is a future FIXME.
9667 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9668 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9669 << IsCPUSpecificCPUDispatchMVType;
9670 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9671 return true;
9672 }
9673
9674 if (HasNonMultiVersionAttributes(NewFD, MVType))
9675 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9676 << IsCPUSpecificCPUDispatchMVType;
9677
9678 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9679 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9680 << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9681
9682 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9683 if (NewCXXFD->isVirtual())
9684 return S.Diag(NewCXXFD->getLocation(),
9685 diag::err_multiversion_doesnt_support)
9686 << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9687
9688 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9689 return S.Diag(NewCXXCtor->getLocation(),
9690 diag::err_multiversion_doesnt_support)
9691 << IsCPUSpecificCPUDispatchMVType << Constructors;
9692
9693 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9694 return S.Diag(NewCXXDtor->getLocation(),
9695 diag::err_multiversion_doesnt_support)
9696 << IsCPUSpecificCPUDispatchMVType << Destructors;
9697 }
9698
9699 if (NewFD->isDeleted())
9700 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9701 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9702
9703 if (NewFD->isDefaulted())
9704 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9705 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9706
9707 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9708 MVType == MultiVersionKind::CPUSpecific))
9709 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9710 << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9711
9712 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9713 const auto *NewType = cast<FunctionType>(NewQType);
9714 QualType NewReturnType = NewType->getReturnType();
9715
9716 if (NewReturnType->isUndeducedType())
9717 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9718 << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9719
9720 // Only allow transition to MultiVersion if it hasn't been used.
9721 if (OldFD && CausesMV && OldFD->isUsed(false))
9722 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9723
9724 // Ensure the return type is identical.
9725 if (OldFD) {
9726 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9727 const auto *OldType = cast<FunctionType>(OldQType);
9728 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9729 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9730
9731 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9732 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9733 << CallingConv;
9734
9735 QualType OldReturnType = OldType->getReturnType();
9736
9737 if (OldReturnType != NewReturnType)
9738 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9739 << ReturnType;
9740
9741 if (OldFD->isConstexpr() != NewFD->isConstexpr())
9742 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9743 << ConstexprSpec;
9744
9745 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9746 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9747 << InlineSpec;
9748
9749 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9750 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9751 << StorageClass;
9752
9753 if (OldFD->isExternC() != NewFD->isExternC())
9754 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9755 << Linkage;
9756
9757 if (S.CheckEquivalentExceptionSpec(
9758 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9759 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9760 return true;
9761 }
9762 return false;
9763}
9764
9765/// Check the validity of a multiversion function declaration that is the
9766/// first of its kind. Also sets the multiversion'ness' of the function itself.
9767///
9768/// This sets NewFD->isInvalidDecl() to true if there was an error.
9769///
9770/// Returns true if there was an error, false otherwise.
9771static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9772 MultiVersionKind MVType,
9773 const TargetAttr *TA) {
9774 assert(MVType != MultiVersionKind::None &&
9775 "Function lacks multiversion attribute");
9776
9777 // Target only causes MV if it is default, otherwise this is a normal
9778 // function.
9779 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9780 return false;
9781
9782 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9783 FD->setInvalidDecl();
9784 return true;
9785 }
9786
9787 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9788 FD->setInvalidDecl();
9789 return true;
9790 }
9791
9792 FD->setIsMultiVersion();
9793 return false;
9794}
9795
9796static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9797 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9798 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9799 return true;
9800 }
9801
9802 return false;
9803}
9804
9805static bool CheckTargetCausesMultiVersioning(
9806 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9807 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9808 LookupResult &Previous) {
9809 const auto *OldTA = OldFD->getAttr<TargetAttr>();
9810 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9811 // Sort order doesn't matter, it just needs to be consistent.
9812 llvm::sort(NewParsed.Features);
9813
9814 // If the old decl is NOT MultiVersioned yet, and we don't cause that
9815 // to change, this is a simple redeclaration.
9816 if (!NewTA->isDefaultVersion() &&
9817 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9818 return false;
9819
9820 // Otherwise, this decl causes MultiVersioning.
9821 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9822 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9823 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9824 NewFD->setInvalidDecl();
9825 return true;
9826 }
9827
9828 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9829 MultiVersionKind::Target)) {
9830 NewFD->setInvalidDecl();
9831 return true;
9832 }
9833
9834 if (CheckMultiVersionValue(S, NewFD)) {
9835 NewFD->setInvalidDecl();
9836 return true;
9837 }
9838
9839 // If this is 'default', permit the forward declaration.
9840 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9841 Redeclaration = true;
9842 OldDecl = OldFD;
9843 OldFD->setIsMultiVersion();
9844 NewFD->setIsMultiVersion();
9845 return false;
9846 }
9847
9848 if (CheckMultiVersionValue(S, OldFD)) {
9849 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9850 NewFD->setInvalidDecl();
9851 return true;
9852 }
9853
9854 TargetAttr::ParsedTargetAttr OldParsed =
9855 OldTA->parse(std::less<std::string>());
9856
9857 if (OldParsed == NewParsed) {
9858 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9859 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9860 NewFD->setInvalidDecl();
9861 return true;
9862 }
9863
9864 for (const auto *FD : OldFD->redecls()) {
9865 const auto *CurTA = FD->getAttr<TargetAttr>();
9866 // We allow forward declarations before ANY multiversioning attributes, but
9867 // nothing after the fact.
9868 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9869 (!CurTA || CurTA->isInherited())) {
9870 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9871 << 0;
9872 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9873 NewFD->setInvalidDecl();
9874 return true;
9875 }
9876 }
9877
9878 OldFD->setIsMultiVersion();
9879 NewFD->setIsMultiVersion();
9880 Redeclaration = false;
9881 MergeTypeWithPrevious = false;
9882 OldDecl = nullptr;
9883 Previous.clear();
9884 return false;
9885}
9886
9887/// Check the validity of a new function declaration being added to an existing
9888/// multiversioned declaration collection.
9889static bool CheckMultiVersionAdditionalDecl(
9890 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9891 MultiVersionKind NewMVType, const TargetAttr *NewTA,
9892 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9893 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9894 LookupResult &Previous) {
9895
9896 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9897 // Disallow mixing of multiversioning types.
9898 if ((OldMVType == MultiVersionKind::Target &&
9899 NewMVType != MultiVersionKind::Target) ||
9900 (NewMVType == MultiVersionKind::Target &&
9901 OldMVType != MultiVersionKind::Target)) {
9902 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9903 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9904 NewFD->setInvalidDecl();
9905 return true;
9906 }
9907
9908 TargetAttr::ParsedTargetAttr NewParsed;
9909 if (NewTA) {
9910 NewParsed = NewTA->parse();
9911 llvm::sort(NewParsed.Features);
9912 }
9913
9914 bool UseMemberUsingDeclRules =
9915 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9916
9917 // Next, check ALL non-overloads to see if this is a redeclaration of a
9918 // previous member of the MultiVersion set.
9919 for (NamedDecl *ND : Previous) {
9920 FunctionDecl *CurFD = ND->getAsFunction();
9921 if (!CurFD)
9922 continue;
9923 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9924 continue;
9925
9926 if (NewMVType == MultiVersionKind::Target) {
9927 const auto *CurTA = CurFD->getAttr<TargetAttr>();
9928 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9929 NewFD->setIsMultiVersion();
9930 Redeclaration = true;
9931 OldDecl = ND;
9932 return false;
9933 }
9934
9935 TargetAttr::ParsedTargetAttr CurParsed =
9936 CurTA->parse(std::less<std::string>());
9937 if (CurParsed == NewParsed) {
9938 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9939 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9940 NewFD->setInvalidDecl();
9941 return true;
9942 }
9943 } else {
9944 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9945 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9946 // Handle CPUDispatch/CPUSpecific versions.
9947 // Only 1 CPUDispatch function is allowed, this will make it go through
9948 // the redeclaration errors.
9949 if (NewMVType == MultiVersionKind::CPUDispatch &&
9950 CurFD->hasAttr<CPUDispatchAttr>()) {
9951 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9952 std::equal(
9953 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9954 NewCPUDisp->cpus_begin(),
9955 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9956 return Cur->getName() == New->getName();
9957 })) {
9958 NewFD->setIsMultiVersion();
9959 Redeclaration = true;
9960 OldDecl = ND;
9961 return false;
9962 }
9963
9964 // If the declarations don't match, this is an error condition.
9965 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9966 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9967 NewFD->setInvalidDecl();
9968 return true;
9969 }
9970 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9971
9972 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9973 std::equal(
9974 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9975 NewCPUSpec->cpus_begin(),
9976 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9977 return Cur->getName() == New->getName();
9978 })) {
9979 NewFD->setIsMultiVersion();
9980 Redeclaration = true;
9981 OldDecl = ND;
9982 return false;
9983 }
9984
9985 // Only 1 version of CPUSpecific is allowed for each CPU.
9986 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9987 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9988 if (CurII == NewII) {
9989 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9990 << NewII;
9991 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9992 NewFD->setInvalidDecl();
9993 return true;
9994 }
9995 }
9996 }
9997 }
9998 // If the two decls aren't the same MVType, there is no possible error
9999 // condition.
10000 }
10001 }
10002
10003 // Else, this is simply a non-redecl case. Checking the 'value' is only
10004 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10005 // handled in the attribute adding step.
10006 if (NewMVType == MultiVersionKind::Target &&
10007 CheckMultiVersionValue(S, NewFD)) {
10008 NewFD->setInvalidDecl();
10009 return true;
10010 }
10011
10012 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10013 !OldFD->isMultiVersion(), NewMVType)) {
10014 NewFD->setInvalidDecl();
10015 return true;
10016 }
10017
10018 // Permit forward declarations in the case where these two are compatible.
10019 if (!OldFD->isMultiVersion()) {
10020 OldFD->setIsMultiVersion();
10021 NewFD->setIsMultiVersion();
10022 Redeclaration = true;
10023 OldDecl = OldFD;
10024 return false;
10025 }
10026
10027 NewFD->setIsMultiVersion();
10028 Redeclaration = false;
10029 MergeTypeWithPrevious = false;
10030 OldDecl = nullptr;
10031 Previous.clear();
10032 return false;
10033}
10034
10035
10036/// Check the validity of a mulitversion function declaration.
10037/// Also sets the multiversion'ness' of the function itself.
10038///
10039/// This sets NewFD->isInvalidDecl() to true if there was an error.
10040///
10041/// Returns true if there was an error, false otherwise.
10042static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10043 bool &Redeclaration, NamedDecl *&OldDecl,
10044 bool &MergeTypeWithPrevious,
10045 LookupResult &Previous) {
10046 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10047 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10048 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10049
10050 // Mixing Multiversioning types is prohibited.
10051 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10052 (NewCPUDisp && NewCPUSpec)) {
10053 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10054 NewFD->setInvalidDecl();
10055 return true;
10056 }
10057
10058 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10059
10060 // Main isn't allowed to become a multiversion function, however it IS
10061 // permitted to have 'main' be marked with the 'target' optimization hint.
10062 if (NewFD->isMain()) {
10063 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10064 MVType == MultiVersionKind::CPUDispatch ||
10065 MVType == MultiVersionKind::CPUSpecific) {
10066 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10067 NewFD->setInvalidDecl();
10068 return true;
10069 }
10070 return false;
10071 }
10072
10073 if (!OldDecl || !OldDecl->getAsFunction() ||
10074 OldDecl->getDeclContext()->getRedeclContext() !=
10075 NewFD->getDeclContext()->getRedeclContext()) {
10076 // If there's no previous declaration, AND this isn't attempting to cause
10077 // multiversioning, this isn't an error condition.
10078 if (MVType == MultiVersionKind::None)
10079 return false;
10080 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10081 }
10082
10083 FunctionDecl *OldFD = OldDecl->getAsFunction();
10084
10085 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10086 return false;
10087
10088 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10089 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10090 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10091 NewFD->setInvalidDecl();
10092 return true;
10093 }
10094
10095 // Handle the target potentially causes multiversioning case.
10096 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10097 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10098 Redeclaration, OldDecl,
10099 MergeTypeWithPrevious, Previous);
10100
10101 // At this point, we have a multiversion function decl (in OldFD) AND an
10102 // appropriate attribute in the current function decl. Resolve that these are
10103 // still compatible with previous declarations.
10104 return CheckMultiVersionAdditionalDecl(
10105 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10106 OldDecl, MergeTypeWithPrevious, Previous);
10107}
10108
10109/// Perform semantic checking of a new function declaration.
10110///
10111/// Performs semantic analysis of the new function declaration
10112/// NewFD. This routine performs all semantic checking that does not
10113/// require the actual declarator involved in the declaration, and is
10114/// used both for the declaration of functions as they are parsed
10115/// (called via ActOnDeclarator) and for the declaration of functions
10116/// that have been instantiated via C++ template instantiation (called
10117/// via InstantiateDecl).
10118///
10119/// \param IsMemberSpecialization whether this new function declaration is
10120/// a member specialization (that replaces any definition provided by the
10121/// previous declaration).
10122///
10123/// This sets NewFD->isInvalidDecl() to true if there was an error.
10124///
10125/// \returns true if the function declaration is a redeclaration.
10126bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10127 LookupResult &Previous,
10128 bool IsMemberSpecialization) {
10129 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10130 "Variably modified return types are not handled here");
10131
10132 // Determine whether the type of this function should be merged with
10133 // a previous visible declaration. This never happens for functions in C++,
10134 // and always happens in C if the previous declaration was visible.
10135 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10136 !Previous.isShadowed();
10137
10138 bool Redeclaration = false;
10139 NamedDecl *OldDecl = nullptr;
10140 bool MayNeedOverloadableChecks = false;
10141
10142 // Merge or overload the declaration with an existing declaration of
10143 // the same name, if appropriate.
10144 if (!Previous.empty()) {
10145 // Determine whether NewFD is an overload of PrevDecl or
10146 // a declaration that requires merging. If it's an overload,
10147 // there's no more work to do here; we'll just add the new
10148 // function to the scope.
10149 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10150 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10151 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10152 Redeclaration = true;
10153 OldDecl = Candidate;
10154 }
10155 } else {
10156 MayNeedOverloadableChecks = true;
10157 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10158 /*NewIsUsingDecl*/ false)) {
10159 case Ovl_Match:
10160 Redeclaration = true;
10161 break;
10162
10163 case Ovl_NonFunction:
10164 Redeclaration = true;
10165 break;
10166
10167 case Ovl_Overload:
10168 Redeclaration = false;
10169 break;
10170 }
10171 }
10172 }
10173
10174 // Check for a previous extern "C" declaration with this name.
10175 if (!Redeclaration &&
10176 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10177 if (!Previous.empty()) {
10178 // This is an extern "C" declaration with the same name as a previous
10179 // declaration, and thus redeclares that entity...
10180 Redeclaration = true;
10181 OldDecl = Previous.getFoundDecl();
10182 MergeTypeWithPrevious = false;
10183
10184 // ... except in the presence of __attribute__((overloadable)).
10185 if (OldDecl->hasAttr<OverloadableAttr>() ||
10186 NewFD->hasAttr<OverloadableAttr>()) {
10187 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10188 MayNeedOverloadableChecks = true;
10189 Redeclaration = false;
10190 OldDecl = nullptr;
10191 }
10192 }
10193 }
10194 }
10195
10196 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10197 MergeTypeWithPrevious, Previous))
10198 return Redeclaration;
10199
10200 // C++11 [dcl.constexpr]p8:
10201 // A constexpr specifier for a non-static member function that is not
10202 // a constructor declares that member function to be const.
10203 //
10204 // This needs to be delayed until we know whether this is an out-of-line
10205 // definition of a static member function.
10206 //
10207 // This rule is not present in C++1y, so we produce a backwards
10208 // compatibility warning whenever it happens in C++11.
10209 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10210 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10211 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10212 !MD->getMethodQualifiers().hasConst()) {
10213 CXXMethodDecl *OldMD = nullptr;
10214 if (OldDecl)
10215 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10216 if (!OldMD || !OldMD->isStatic()) {
10217 const FunctionProtoType *FPT =
10218 MD->getType()->castAs<FunctionProtoType>();
10219 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10220 EPI.TypeQuals.addConst();
10221 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10222 FPT->getParamTypes(), EPI));
10223
10224 // Warn that we did this, if we're not performing template instantiation.
10225 // In that case, we'll have warned already when the template was defined.
10226 if (!inTemplateInstantiation()) {
10227 SourceLocation AddConstLoc;
10228 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10229 .IgnoreParens().getAs<FunctionTypeLoc>())
10230 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10231
10232 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10233 << FixItHint::CreateInsertion(AddConstLoc, " const");
10234 }
10235 }
10236 }
10237
10238 if (Redeclaration) {
10239 // NewFD and OldDecl represent declarations that need to be
10240 // merged.
10241 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10242 NewFD->setInvalidDecl();
10243 return Redeclaration;
10244 }
10245
10246 Previous.clear();
10247 Previous.addDecl(OldDecl);
10248
10249 if (FunctionTemplateDecl *OldTemplateDecl =
10250 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10251 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10252 FunctionTemplateDecl *NewTemplateDecl
10253 = NewFD->getDescribedFunctionTemplate();
10254 assert(NewTemplateDecl && "Template/non-template mismatch");
10255
10256 // The call to MergeFunctionDecl above may have created some state in
10257 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10258 // can add it as a redeclaration.
10259 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10260
10261 NewFD->setPreviousDeclaration(OldFD);
10262 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10263 if (NewFD->isCXXClassMember()) {
10264 NewFD->setAccess(OldTemplateDecl->getAccess());
10265 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10266 }
10267
10268 // If this is an explicit specialization of a member that is a function
10269 // template, mark it as a member specialization.
10270 if (IsMemberSpecialization &&
10271 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10272 NewTemplateDecl->setMemberSpecialization();
10273 assert(OldTemplateDecl->isMemberSpecialization());
10274 // Explicit specializations of a member template do not inherit deleted
10275 // status from the parent member template that they are specializing.
10276 if (OldFD->isDeleted()) {
10277 // FIXME: This assert will not hold in the presence of modules.
10278 assert(OldFD->getCanonicalDecl() == OldFD);
10279 // FIXME: We need an update record for this AST mutation.
10280 OldFD->setDeletedAsWritten(false);
10281 }
10282 }
10283
10284 } else {
10285 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10286 auto *OldFD = cast<FunctionDecl>(OldDecl);
10287 // This needs to happen first so that 'inline' propagates.
10288 NewFD->setPreviousDeclaration(OldFD);
10289 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10290 if (NewFD->isCXXClassMember())
10291 NewFD->setAccess(OldFD->getAccess());
10292 }
10293 }
10294 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10295 !NewFD->getAttr<OverloadableAttr>()) {
10296 assert((Previous.empty() ||
10297 llvm::any_of(Previous,
10298 [](const NamedDecl *ND) {
10299 return ND->hasAttr<OverloadableAttr>();
10300 })) &&
10301 "Non-redecls shouldn't happen without overloadable present");
10302
10303 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10304 const auto *FD = dyn_cast<FunctionDecl>(ND);
10305 return FD && !FD->hasAttr<OverloadableAttr>();
10306 });
10307
10308 if (OtherUnmarkedIter != Previous.end()) {
10309 Diag(NewFD->getLocation(),
10310 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10311 Diag((*OtherUnmarkedIter)->getLocation(),
10312 diag::note_attribute_overloadable_prev_overload)
10313 << false;
10314
10315 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10316 }
10317 }
10318
10319 // Semantic checking for this function declaration (in isolation).
10320
10321 if (getLangOpts().CPlusPlus) {
10322 // C++-specific checks.
10323 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10324 CheckConstructor(Constructor);
10325 } else if (CXXDestructorDecl *Destructor =
10326 dyn_cast<CXXDestructorDecl>(NewFD)) {
10327 CXXRecordDecl *Record = Destructor->getParent();
10328 QualType ClassType = Context.getTypeDeclType(Record);
10329
10330 // FIXME: Shouldn't we be able to perform this check even when the class
10331 // type is dependent? Both gcc and edg can handle that.
10332 if (!ClassType->isDependentType()) {
10333 DeclarationName Name
10334 = Context.DeclarationNames.getCXXDestructorName(
10335 Context.getCanonicalType(ClassType));
10336 if (NewFD->getDeclName() != Name) {
10337 Diag(NewFD->getLocation(), diag::err_destructor_name);
10338 NewFD->setInvalidDecl();
10339 return Redeclaration;
10340 }
10341 }
10342 } else if (CXXConversionDecl *Conversion
10343 = dyn_cast<CXXConversionDecl>(NewFD)) {
10344 ActOnConversionDeclarator(Conversion);
10345 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10346 if (auto *TD = Guide->getDescribedFunctionTemplate())
10347 CheckDeductionGuideTemplate(TD);
10348
10349 // A deduction guide is not on the list of entities that can be
10350 // explicitly specialized.
10351 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10352 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10353 << /*explicit specialization*/ 1;
10354 }
10355
10356 // Find any virtual functions that this function overrides.
10357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10358 if (!Method->isFunctionTemplateSpecialization() &&
10359 !Method->getDescribedFunctionTemplate() &&
10360 Method->isCanonicalDecl()) {
10361 if (AddOverriddenMethods(Method->getParent(), Method)) {
10362 // If the function was marked as "static", we have a problem.
10363 if (NewFD->getStorageClass() == SC_Static) {
10364 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10365 }
10366 }
10367 }
10368
10369 if (Method->isStatic())
10370 checkThisInStaticMemberFunctionType(Method);
10371 }
10372
10373 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10374 if (NewFD->isOverloadedOperator() &&
10375 CheckOverloadedOperatorDeclaration(NewFD)) {
10376 NewFD->setInvalidDecl();
10377 return Redeclaration;
10378 }
10379
10380 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10381 if (NewFD->getLiteralIdentifier() &&
10382 CheckLiteralOperatorDeclaration(NewFD)) {
10383 NewFD->setInvalidDecl();
10384 return Redeclaration;
10385 }
10386
10387 // In C++, check default arguments now that we have merged decls. Unless
10388 // the lexical context is the class, because in this case this is done
10389 // during delayed parsing anyway.
10390 if (!CurContext->isRecord())
10391 CheckCXXDefaultArguments(NewFD);
10392
10393 // If this function declares a builtin function, check the type of this
10394 // declaration against the expected type for the builtin.
10395 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10396 ASTContext::GetBuiltinTypeError Error;
10397 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10398 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10399 // If the type of the builtin differs only in its exception
10400 // specification, that's OK.
10401 // FIXME: If the types do differ in this way, it would be better to
10402 // retain the 'noexcept' form of the type.
10403 if (!T.isNull() &&
10404 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10405 NewFD->getType()))
10406 // The type of this function differs from the type of the builtin,
10407 // so forget about the builtin entirely.
10408 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10409 }
10410
10411 // If this function is declared as being extern "C", then check to see if
10412 // the function returns a UDT (class, struct, or union type) that is not C
10413 // compatible, and if it does, warn the user.
10414 // But, issue any diagnostic on the first declaration only.
10415 if (Previous.empty() && NewFD->isExternC()) {
10416 QualType R = NewFD->getReturnType();
10417 if (R->isIncompleteType() && !R->isVoidType())
10418 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10419 << NewFD << R;
10420 else if (!R.isPODType(Context) && !R->isVoidType() &&
10421 !R->isObjCObjectPointerType())
10422 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10423 }
10424
10425 // C++1z [dcl.fct]p6:
10426 // [...] whether the function has a non-throwing exception-specification
10427 // [is] part of the function type
10428 //
10429 // This results in an ABI break between C++14 and C++17 for functions whose
10430 // declared type includes an exception-specification in a parameter or
10431 // return type. (Exception specifications on the function itself are OK in
10432 // most cases, and exception specifications are not permitted in most other
10433 // contexts where they could make it into a mangling.)
10434 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10435 auto HasNoexcept = [&](QualType T) -> bool {
10436 // Strip off declarator chunks that could be between us and a function
10437 // type. We don't need to look far, exception specifications are very
10438 // restricted prior to C++17.
10439 if (auto *RT = T->getAs<ReferenceType>())
10440 T = RT->getPointeeType();
10441 else if (T->isAnyPointerType())
10442 T = T->getPointeeType();
10443 else if (auto *MPT = T->getAs<MemberPointerType>())
10444 T = MPT->getPointeeType();
10445 if (auto *FPT = T->getAs<FunctionProtoType>())
10446 if (FPT->isNothrow())
10447 return true;
10448 return false;
10449 };
10450
10451 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10452 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10453 for (QualType T : FPT->param_types())
10454 AnyNoexcept |= HasNoexcept(T);
10455 if (AnyNoexcept)
10456 Diag(NewFD->getLocation(),
10457 diag::warn_cxx17_compat_exception_spec_in_signature)
10458 << NewFD;
10459 }
10460
10461 if (!Redeclaration && LangOpts.CUDA)
10462 checkCUDATargetOverload(NewFD, Previous);
10463 }
10464 return Redeclaration;
10465}
10466
10467void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10468 // C++11 [basic.start.main]p3:
10469 // A program that [...] declares main to be inline, static or
10470 // constexpr is ill-formed.
10471 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10472 // appear in a declaration of main.
10473 // static main is not an error under C99, but we should warn about it.
10474 // We accept _Noreturn main as an extension.
10475 if (FD->getStorageClass() == SC_Static)
10476 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10477 ? diag::err_static_main : diag::warn_static_main)
10478 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10479 if (FD->isInlineSpecified())
10480 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10481 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10482 if (DS.isNoreturnSpecified()) {
10483 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10484 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10485 Diag(NoreturnLoc, diag::ext_noreturn_main);
10486 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10487 << FixItHint::CreateRemoval(NoreturnRange);
10488 }
10489 if (FD->isConstexpr()) {
10490 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10491 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10492 FD->setConstexpr(false);
10493 }
10494
10495 if (getLangOpts().OpenCL) {
10496 Diag(FD->getLocation(), diag::err_opencl_no_main)
10497 << FD->hasAttr<OpenCLKernelAttr>();
10498 FD->setInvalidDecl();
10499 return;
10500 }
10501
10502 QualType T = FD->getType();
10503 assert(T->isFunctionType() && "function decl is not of function type");
10504 const FunctionType* FT = T->castAs<FunctionType>();
10505
10506 // Set default calling convention for main()
10507 if (FT->getCallConv() != CC_C) {
10508 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10509 FD->setType(QualType(FT, 0));
10510 T = Context.getCanonicalType(FD->getType());
10511 }
10512
10513 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10514 // In C with GNU extensions we allow main() to have non-integer return
10515 // type, but we should warn about the extension, and we disable the
10516 // implicit-return-zero rule.
10517
10518 // GCC in C mode accepts qualified 'int'.
10519 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10520 FD->setHasImplicitReturnZero(true);
10521 else {
10522 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10523 SourceRange RTRange = FD->getReturnTypeSourceRange();
10524 if (RTRange.isValid())
10525 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10526 << FixItHint::CreateReplacement(RTRange, "int");
10527 }
10528 } else {
10529 // In C and C++, main magically returns 0 if you fall off the end;
10530 // set the flag which tells us that.
10531 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10532
10533 // All the standards say that main() should return 'int'.
10534 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10535 FD->setHasImplicitReturnZero(true);
10536 else {
10537 // Otherwise, this is just a flat-out error.
10538 SourceRange RTRange = FD->getReturnTypeSourceRange();
10539 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10540 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10541 : FixItHint());
10542 FD->setInvalidDecl(true);
10543 }
10544 }
10545
10546 // Treat protoless main() as nullary.
10547 if (isa<FunctionNoProtoType>(FT)) return;
10548
10549 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10550 unsigned nparams = FTP->getNumParams();
10551 assert(FD->getNumParams() == nparams);
10552
10553 bool HasExtraParameters = (nparams > 3);
10554
10555 if (FTP->isVariadic()) {
10556 Diag(FD->getLocation(), diag::ext_variadic_main);
10557 // FIXME: if we had information about the location of the ellipsis, we
10558 // could add a FixIt hint to remove it as a parameter.
10559 }
10560
10561 // Darwin passes an undocumented fourth argument of type char**. If
10562 // other platforms start sprouting these, the logic below will start
10563 // getting shifty.
10564 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10565 HasExtraParameters = false;
10566
10567 if (HasExtraParameters) {
10568 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10569 FD->setInvalidDecl(true);
10570 nparams = 3;
10571 }
10572
10573 // FIXME: a lot of the following diagnostics would be improved
10574 // if we had some location information about types.
10575
10576 QualType CharPP =
10577 Context.getPointerType(Context.getPointerType(Context.CharTy));
10578 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10579
10580 for (unsigned i = 0; i < nparams; ++i) {
10581 QualType AT = FTP->getParamType(i);
10582
10583 bool mismatch = true;
10584
10585 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10586 mismatch = false;
10587 else if (Expected[i] == CharPP) {
10588 // As an extension, the following forms are okay:
10589 // char const **
10590 // char const * const *
10591 // char * const *
10592
10593 QualifierCollector qs;
10594 const PointerType* PT;
10595 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10596 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10597 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10598 Context.CharTy)) {
10599 qs.removeConst();
10600 mismatch = !qs.empty();
10601 }
10602 }
10603
10604 if (mismatch) {
10605 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10606 // TODO: suggest replacing given type with expected type
10607 FD->setInvalidDecl(true);
10608 }
10609 }
10610
10611 if (nparams == 1 && !FD->isInvalidDecl()) {
10612 Diag(FD->getLocation(), diag::warn_main_one_arg);
10613 }
10614
10615 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10616 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10617 FD->setInvalidDecl();
10618 }
10619}
10620
10621void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10622 QualType T = FD->getType();
10623 assert(T->isFunctionType() && "function decl is not of function type");
10624 const FunctionType *FT = T->castAs<FunctionType>();
10625
10626 // Set an implicit return of 'zero' if the function can return some integral,
10627 // enumeration, pointer or nullptr type.
10628 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10629 FT->getReturnType()->isAnyPointerType() ||
10630 FT->getReturnType()->isNullPtrType())
10631 // DllMain is exempt because a return value of zero means it failed.
10632 if (FD->getName() != "DllMain")
10633 FD->setHasImplicitReturnZero(true);
10634
10635 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10636 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10637 FD->setInvalidDecl();
10638 }
10639}
10640
10641bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10642 // FIXME: Need strict checking. In C89, we need to check for
10643 // any assignment, increment, decrement, function-calls, or
10644 // commas outside of a sizeof. In C99, it's the same list,
10645 // except that the aforementioned are allowed in unevaluated
10646 // expressions. Everything else falls under the
10647 // "may accept other forms of constant expressions" exception.
10648 // (We never end up here for C++, so the constant expression
10649 // rules there don't matter.)
10650 const Expr *Culprit;
10651 if (Init->isConstantInitializer(Context, false, &Culprit))
10652 return false;
10653 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10654 << Culprit->getSourceRange();
10655 return true;
10656}
10657
10658namespace {
10659 // Visits an initialization expression to see if OrigDecl is evaluated in
10660 // its own initialization and throws a warning if it does.
10661 class SelfReferenceChecker
10662 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10663 Sema &S;
10664 Decl *OrigDecl;
10665 bool isRecordType;
10666 bool isPODType;
10667 bool isReferenceType;
10668
10669 bool isInitList;
10670 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10671
10672 public:
10673 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10674
10675 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10676 S(S), OrigDecl(OrigDecl) {
10677 isPODType = false;
10678 isRecordType = false;
10679 isReferenceType = false;
10680 isInitList = false;
10681 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10682 isPODType = VD->getType().isPODType(S.Context);
10683 isRecordType = VD->getType()->isRecordType();
10684 isReferenceType = VD->getType()->isReferenceType();
10685 }
10686 }
10687
10688 // For most expressions, just call the visitor. For initializer lists,
10689 // track the index of the field being initialized since fields are
10690 // initialized in order allowing use of previously initialized fields.
10691 void CheckExpr(Expr *E) {
10692 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10693 if (!InitList) {
10694 Visit(E);
10695 return;
10696 }
10697
10698 // Track and increment the index here.
10699 isInitList = true;
10700 InitFieldIndex.push_back(0);
10701 for (auto Child : InitList->children()) {
10702 CheckExpr(cast<Expr>(Child));
10703 ++InitFieldIndex.back();
10704 }
10705 InitFieldIndex.pop_back();
10706 }
10707
10708 // Returns true if MemberExpr is checked and no further checking is needed.
10709 // Returns false if additional checking is required.
10710 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10711 llvm::SmallVector<FieldDecl*, 4> Fields;
10712 Expr *Base = E;
10713 bool ReferenceField = false;
10714
10715 // Get the field members used.
10716 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10717 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10718 if (!FD)
10719 return false;
10720 Fields.push_back(FD);
10721 if (FD->getType()->isReferenceType())
10722 ReferenceField = true;
10723 Base = ME->getBase()->IgnoreParenImpCasts();
10724 }
10725
10726 // Keep checking only if the base Decl is the same.
10727 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10728 if (!DRE || DRE->getDecl() != OrigDecl)
10729 return false;
10730
10731 // A reference field can be bound to an unininitialized field.
10732 if (CheckReference && !ReferenceField)
10733 return true;
10734
10735 // Convert FieldDecls to their index number.
10736 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10737 for (const FieldDecl *I : llvm::reverse(Fields))
10738 UsedFieldIndex.push_back(I->getFieldIndex());
10739
10740 // See if a warning is needed by checking the first difference in index
10741 // numbers. If field being used has index less than the field being
10742 // initialized, then the use is safe.
10743 for (auto UsedIter = UsedFieldIndex.begin(),
10744 UsedEnd = UsedFieldIndex.end(),
10745 OrigIter = InitFieldIndex.begin(),
10746 OrigEnd = InitFieldIndex.end();
10747 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10748 if (*UsedIter < *OrigIter)
10749 return true;
10750 if (*UsedIter > *OrigIter)
10751 break;
10752 }
10753
10754 // TODO: Add a different warning which will print the field names.
10755 HandleDeclRefExpr(DRE);
10756 return true;
10757 }
10758
10759 // For most expressions, the cast is directly above the DeclRefExpr.
10760 // For conditional operators, the cast can be outside the conditional
10761 // operator if both expressions are DeclRefExpr's.
10762 void HandleValue(Expr *E) {
10763 E = E->IgnoreParens();
10764 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10765 HandleDeclRefExpr(DRE);
10766 return;
10767 }
10768
10769 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10770 Visit(CO->getCond());
10771 HandleValue(CO->getTrueExpr());
10772 HandleValue(CO->getFalseExpr());
10773 return;
10774 }
10775
10776 if (BinaryConditionalOperator *BCO =
10777 dyn_cast<BinaryConditionalOperator>(E)) {
10778 Visit(BCO->getCond());
10779 HandleValue(BCO->getFalseExpr());
10780 return;
10781 }
10782
10783 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10784 HandleValue(OVE->getSourceExpr());
10785 return;
10786 }
10787
10788 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10789 if (BO->getOpcode() == BO_Comma) {
10790 Visit(BO->getLHS());
10791 HandleValue(BO->getRHS());
10792 return;
10793 }
10794 }
10795
10796 if (isa<MemberExpr>(E)) {
10797 if (isInitList) {
10798 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10799 false /*CheckReference*/))
10800 return;
10801 }
10802
10803 Expr *Base = E->IgnoreParenImpCasts();
10804 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10805 // Check for static member variables and don't warn on them.
10806 if (!isa<FieldDecl>(ME->getMemberDecl()))
10807 return;
10808 Base = ME->getBase()->IgnoreParenImpCasts();
10809 }
10810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10811 HandleDeclRefExpr(DRE);
10812 return;
10813 }
10814
10815 Visit(E);
10816 }
10817
10818 // Reference types not handled in HandleValue are handled here since all
10819 // uses of references are bad, not just r-value uses.
10820 void VisitDeclRefExpr(DeclRefExpr *E) {
10821 if (isReferenceType)
10822 HandleDeclRefExpr(E);
10823 }
10824
10825 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10826 if (E->getCastKind() == CK_LValueToRValue) {
10827 HandleValue(E->getSubExpr());
10828 return;
10829 }
10830
10831 Inherited::VisitImplicitCastExpr(E);
10832 }
10833
10834 void VisitMemberExpr(MemberExpr *E) {
10835 if (isInitList) {
10836 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10837 return;
10838 }
10839
10840 // Don't warn on arrays since they can be treated as pointers.
10841 if (E->getType()->canDecayToPointerType()) return;
10842
10843 // Warn when a non-static method call is followed by non-static member
10844 // field accesses, which is followed by a DeclRefExpr.
10845 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10846 bool Warn = (MD && !MD->isStatic());
10847 Expr *Base = E->getBase()->IgnoreParenImpCasts();
10848 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10849 if (!isa<FieldDecl>(ME->getMemberDecl()))
10850 Warn = false;
10851 Base = ME->getBase()->IgnoreParenImpCasts();
10852 }
10853
10854 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10855 if (Warn)
10856 HandleDeclRefExpr(DRE);
10857 return;
10858 }
10859
10860 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10861 // Visit that expression.
10862 Visit(Base);
10863 }
10864
10865 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10866 Expr *Callee = E->getCallee();
10867
10868 if (isa<UnresolvedLookupExpr>(Callee))
10869 return Inherited::VisitCXXOperatorCallExpr(E);
10870
10871 Visit(Callee);
10872 for (auto Arg: E->arguments())
10873 HandleValue(Arg->IgnoreParenImpCasts());
10874 }
10875
10876 void VisitUnaryOperator(UnaryOperator *E) {
10877 // For POD record types, addresses of its own members are well-defined.
10878 if (E->getOpcode() == UO_AddrOf && isRecordType &&
10879 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10880 if (!isPODType)
10881 HandleValue(E->getSubExpr());
10882 return;
10883 }
10884
10885 if (E->isIncrementDecrementOp()) {
10886 HandleValue(E->getSubExpr());
10887 return;
10888 }
10889
10890 Inherited::VisitUnaryOperator(E);
10891 }
10892
10893 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10894
10895 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10896 if (E->getConstructor()->isCopyConstructor()) {
10897 Expr *ArgExpr = E->getArg(0);
10898 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10899 if (ILE->getNumInits() == 1)
10900 ArgExpr = ILE->getInit(0);
10901 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10902 if (ICE->getCastKind() == CK_NoOp)
10903 ArgExpr = ICE->getSubExpr();
10904 HandleValue(ArgExpr);
10905 return;
10906 }
10907 Inherited::VisitCXXConstructExpr(E);
10908 }
10909
10910 void VisitCallExpr(CallExpr *E) {
10911 // Treat std::move as a use.
10912 if (E->isCallToStdMove()) {
10913 HandleValue(E->getArg(0));
10914 return;
10915 }
10916
10917 Inherited::VisitCallExpr(E);
10918 }
10919
10920 void VisitBinaryOperator(BinaryOperator *E) {
10921 if (E->isCompoundAssignmentOp()) {
10922 HandleValue(E->getLHS());
10923 Visit(E->getRHS());
10924 return;
10925 }
10926
10927 Inherited::VisitBinaryOperator(E);
10928 }
10929
10930 // A custom visitor for BinaryConditionalOperator is needed because the
10931 // regular visitor would check the condition and true expression separately
10932 // but both point to the same place giving duplicate diagnostics.
10933 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10934 Visit(E->getCond());
10935 Visit(E->getFalseExpr());
10936 }
10937
10938 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10939 Decl* ReferenceDecl = DRE->getDecl();
10940 if (OrigDecl != ReferenceDecl) return;
10941 unsigned diag;
10942 if (isReferenceType) {
10943 diag = diag::warn_uninit_self_reference_in_reference_init;
10944 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10945 diag = diag::warn_static_self_reference_in_init;
10946 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10947 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10948 DRE->getDecl()->getType()->isRecordType()) {
10949 diag = diag::warn_uninit_self_reference_in_init;
10950 } else {
10951 // Local variables will be handled by the CFG analysis.
10952 return;
10953 }
10954
10955 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10956 S.PDiag(diag)
10957 << DRE->getDecl() << OrigDecl->getLocation()
10958 << DRE->getSourceRange());
10959 }
10960 };
10961
10962 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10963 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10964 bool DirectInit) {
10965 // Parameters arguments are occassionially constructed with itself,
10966 // for instance, in recursive functions. Skip them.
10967 if (isa<ParmVarDecl>(OrigDecl))
10968 return;
10969
10970 E = E->IgnoreParens();
10971
10972 // Skip checking T a = a where T is not a record or reference type.
10973 // Doing so is a way to silence uninitialized warnings.
10974 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10975 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10976 if (ICE->getCastKind() == CK_LValueToRValue)
10977 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10978 if (DRE->getDecl() == OrigDecl)
10979 return;
10980
10981 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10982 }
10983} // end anonymous namespace
10984
10985namespace {
10986 // Simple wrapper to add the name of a variable or (if no variable is
10987 // available) a DeclarationName into a diagnostic.
10988 struct VarDeclOrName {
10989 VarDecl *VDecl;
10990 DeclarationName Name;
10991
10992 friend const Sema::SemaDiagnosticBuilder &
10993 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10994 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10995 }
10996 };
10997} // end anonymous namespace
10998
10999QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11000 DeclarationName Name, QualType Type,
11001 TypeSourceInfo *TSI,
11002 SourceRange Range, bool DirectInit,
11003 Expr *Init) {
11004 bool IsInitCapture = !VDecl;
11005 assert((!VDecl || !VDecl->isInitCapture()) &&
11006 "init captures are expected to be deduced prior to initialization");
11007
11008 VarDeclOrName VN{VDecl, Name};
11009
11010 DeducedType *Deduced = Type->getContainedDeducedType();
11011 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11012
11013 // C++11 [dcl.spec.auto]p3
11014 if (!Init) {
11015 assert(VDecl && "no init for init capture deduction?");
11016
11017 // Except for class argument deduction, and then for an initializing
11018 // declaration only, i.e. no static at class scope or extern.
11019 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11020 VDecl->hasExternalStorage() ||
11021 VDecl->isStaticDataMember()) {
11022 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11023 << VDecl->getDeclName() << Type;
11024 return QualType();
11025 }
11026 }
11027
11028 ArrayRef<Expr*> DeduceInits;
11029 if (Init)
11030 DeduceInits = Init;
11031
11032 if (DirectInit) {
11033 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11034 DeduceInits = PL->exprs();
11035 }
11036
11037 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11038 assert(VDecl && "non-auto type for init capture deduction?");
11039 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11040 InitializationKind Kind = InitializationKind::CreateForInit(
11041 VDecl->getLocation(), DirectInit, Init);
11042 // FIXME: Initialization should not be taking a mutable list of inits.
11043 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11044 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11045 InitsCopy);
11046 }
11047
11048 if (DirectInit) {
11049 if (auto *IL = dyn_cast<InitListExpr>(Init))
11050 DeduceInits = IL->inits();
11051 }
11052
11053 // Deduction only works if we have exactly one source expression.
11054 if (DeduceInits.empty()) {
11055 // It isn't possible to write this directly, but it is possible to
11056 // end up in this situation with "auto x(some_pack...);"
11057 Diag(Init->getBeginLoc(), IsInitCapture
11058 ? diag::err_init_capture_no_expression
11059 : diag::err_auto_var_init_no_expression)
11060 << VN << Type << Range;
11061 return QualType();
11062 }
11063
11064 if (DeduceInits.size() > 1) {
11065 Diag(DeduceInits[1]->getBeginLoc(),
11066 IsInitCapture ? diag::err_init_capture_multiple_expressions
11067 : diag::err_auto_var_init_multiple_expressions)
11068 << VN << Type << Range;
11069 return QualType();
11070 }
11071
11072 Expr *DeduceInit = DeduceInits[0];
11073 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11074 Diag(Init->getBeginLoc(), IsInitCapture
11075 ? diag::err_init_capture_paren_braces
11076 : diag::err_auto_var_init_paren_braces)
11077 << isa<InitListExpr>(Init) << VN << Type << Range;
11078 return QualType();
11079 }
11080
11081 // Expressions default to 'id' when we're in a debugger.
11082 bool DefaultedAnyToId = false;
11083 if (getLangOpts().DebuggerCastResultToId &&
11084 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11085 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11086 if (Result.isInvalid()) {
11087 return QualType();
11088 }
11089 Init = Result.get();
11090 DefaultedAnyToId = true;
11091 }
11092
11093 // C++ [dcl.decomp]p1:
11094 // If the assignment-expression [...] has array type A and no ref-qualifier
11095 // is present, e has type cv A
11096 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11097 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11098 DeduceInit->getType()->isConstantArrayType())
11099 return Context.getQualifiedType(DeduceInit->getType(),
11100 Type.getQualifiers());
11101
11102 QualType DeducedType;
11103 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11104 if (!IsInitCapture)
11105 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11106 else if (isa<InitListExpr>(Init))
11107 Diag(Range.getBegin(),
11108 diag::err_init_capture_deduction_failure_from_init_list)
11109 << VN
11110 << (DeduceInit->getType().isNull() ? TSI->getType()
11111 : DeduceInit->getType())
11112 << DeduceInit->getSourceRange();
11113 else
11114 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11115 << VN << TSI->getType()
11116 << (DeduceInit->getType().isNull() ? TSI->getType()
11117 : DeduceInit->getType())
11118 << DeduceInit->getSourceRange();
11119 }
11120
11121 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11122 // 'id' instead of a specific object type prevents most of our usual
11123 // checks.
11124 // We only want to warn outside of template instantiations, though:
11125 // inside a template, the 'id' could have come from a parameter.
11126 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11127 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11128 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11129 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11130 }
11131
11132 return DeducedType;
11133}
11134
11135bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11136 Expr *Init) {
11137 QualType DeducedType = deduceVarTypeFromInitializer(
11138 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11139 VDecl->getSourceRange(), DirectInit, Init);
11140 if (DeducedType.isNull()) {
11141 VDecl->setInvalidDecl();
11142 return true;
11143 }
11144
11145 VDecl->setType(DeducedType);
11146 assert(VDecl->isLinkageValid());
11147
11148 // In ARC, infer lifetime.
11149 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11150 VDecl->setInvalidDecl();
11151
11152 // If this is a redeclaration, check that the type we just deduced matches
11153 // the previously declared type.
11154 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11155 // We never need to merge the type, because we cannot form an incomplete
11156 // array of auto, nor deduce such a type.
11157 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11158 }
11159
11160 // Check the deduced type is valid for a variable declaration.
11161 CheckVariableDeclarationType(VDecl);
11162 return VDecl->isInvalidDecl();
11163}
11164
11165/// AddInitializerToDecl - Adds the initializer Init to the
11166/// declaration dcl. If DirectInit is true, this is C++ direct
11167/// initialization rather than copy initialization.
11168void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11169 // If there is no declaration, there was an error parsing it. Just ignore
11170 // the initializer.
11171 if (!RealDecl || RealDecl->isInvalidDecl()) {
11172 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11173 return;
11174 }
11175
11176 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11177 // Pure-specifiers are handled in ActOnPureSpecifier.
11178 Diag(Method->getLocation(), diag::err_member_function_initialization)
11179 << Method->getDeclName() << Init->getSourceRange();
11180 Method->setInvalidDecl();
11181 return;
11182 }
11183
11184 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11185 if (!VDecl) {
11186 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11187 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11188 RealDecl->setInvalidDecl();
11189 return;
11190 }
11191
11192 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11193 if (VDecl->getType()->isUndeducedType()) {
11194 // Attempt typo correction early so that the type of the init expression can
11195 // be deduced based on the chosen correction if the original init contains a
11196 // TypoExpr.
11197 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11198 if (!Res.isUsable()) {
11199 RealDecl->setInvalidDecl();
11200 return;
11201 }
11202 Init = Res.get();
11203
11204 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11205 return;
11206 }
11207
11208 // dllimport cannot be used on variable definitions.
11209 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11210 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11211 VDecl->setInvalidDecl();
11212 return;
11213 }
11214
11215 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11216 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11217 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11218 VDecl->setInvalidDecl();
11219 return;
11220 }
11221
11222 if (!VDecl->getType()->isDependentType()) {
11223 // A definition must end up with a complete type, which means it must be
11224 // complete with the restriction that an array type might be completed by
11225 // the initializer; note that later code assumes this restriction.
11226 QualType BaseDeclType = VDecl->getType();
11227 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11228 BaseDeclType = Array->getElementType();
11229 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11230 diag::err_typecheck_decl_incomplete_type)) {
11231 RealDecl->setInvalidDecl();
11232 return;
11233 }
11234
11235 // The variable can not have an abstract class type.
11236 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11237 diag::err_abstract_type_in_decl,
11238 AbstractVariableType))
11239 VDecl->setInvalidDecl();
11240 }
11241
11242 // If adding the initializer will turn this declaration into a definition,
11243 // and we already have a definition for this variable, diagnose or otherwise
11244 // handle the situation.
11245 VarDecl *Def;
11246 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11247 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11248 !VDecl->isThisDeclarationADemotedDefinition() &&
11249 checkVarDeclRedefinition(Def, VDecl))
11250 return;
11251
11252 if (getLangOpts().CPlusPlus) {
11253 // C++ [class.static.data]p4
11254 // If a static data member is of const integral or const
11255 // enumeration type, its declaration in the class definition can
11256 // specify a constant-initializer which shall be an integral
11257 // constant expression (5.19). In that case, the member can appear
11258 // in integral constant expressions. The member shall still be
11259 // defined in a namespace scope if it is used in the program and the
11260 // namespace scope definition shall not contain an initializer.
11261 //
11262 // We already performed a redefinition check above, but for static
11263 // data members we also need to check whether there was an in-class
11264 // declaration with an initializer.
11265 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11266 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11267 << VDecl->getDeclName();
11268 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11269 diag::note_previous_initializer)
11270 << 0;
11271 return;
11272 }
11273
11274 if (VDecl->hasLocalStorage())
11275 setFunctionHasBranchProtectedScope();
11276
11277 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11278 VDecl->setInvalidDecl();
11279 return;
11280 }
11281 }
11282
11283 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11284 // a kernel function cannot be initialized."
11285 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11286 Diag(VDecl->getLocation(), diag::err_local_cant_init);
11287 VDecl->setInvalidDecl();
11288 return;
11289 }
11290
11291 // Get the decls type and save a reference for later, since
11292 // CheckInitializerTypes may change it.
11293 QualType DclT = VDecl->getType(), SavT = DclT;
11294
11295 // Expressions default to 'id' when we're in a debugger
11296 // and we are assigning it to a variable of Objective-C pointer type.
11297 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11298 Init->getType() == Context.UnknownAnyTy) {
11299 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11300 if (Result.isInvalid()) {
11301 VDecl->setInvalidDecl();
11302 return;
11303 }
11304 Init = Result.get();
11305 }
11306
11307 // Perform the initialization.
11308 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11309 if (!VDecl->isInvalidDecl()) {
11310 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11311 InitializationKind Kind = InitializationKind::CreateForInit(
11312 VDecl->getLocation(), DirectInit, Init);
11313
11314 MultiExprArg Args = Init;
11315 if (CXXDirectInit)
11316 Args = MultiExprArg(CXXDirectInit->getExprs(),
11317 CXXDirectInit->getNumExprs());
11318
11319 // Try to correct any TypoExprs in the initialization arguments.
11320 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11321 ExprResult Res = CorrectDelayedTyposInExpr(
11322 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11323 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11324 return Init.Failed() ? ExprError() : E;
11325 });
11326 if (Res.isInvalid()) {
11327 VDecl->setInvalidDecl();
11328 } else if (Res.get() != Args[Idx]) {
11329 Args[Idx] = Res.get();
11330 }
11331 }
11332 if (VDecl->isInvalidDecl())
11333 return;
11334
11335 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11336 /*TopLevelOfInitList=*/false,
11337 /*TreatUnavailableAsInvalid=*/false);
11338 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11339 if (Result.isInvalid()) {
11340 VDecl->setInvalidDecl();
11341 return;
11342 }
11343
11344 Init = Result.getAs<Expr>();
11345 }
11346
11347 // Check for self-references within variable initializers.
11348 // Variables declared within a function/method body (except for references)
11349 // are handled by a dataflow analysis.
11350 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11351 VDecl->getType()->isReferenceType()) {
11352 CheckSelfReference(*this, RealDecl, Init, DirectInit);
11353 }
11354
11355 // If the type changed, it means we had an incomplete type that was
11356 // completed by the initializer. For example:
11357 // int ary[] = { 1, 3, 5 };
11358 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11359 if (!VDecl->isInvalidDecl() && (DclT != SavT))
11360 VDecl->setType(DclT);
11361
11362 if (!VDecl->isInvalidDecl()) {
11363 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11364
11365 if (VDecl->hasAttr<BlocksAttr>())
11366 checkRetainCycles(VDecl, Init);
11367
11368 // It is safe to assign a weak reference into a strong variable.
11369 // Although this code can still have problems:
11370 // id x = self.weakProp;
11371 // id y = self.weakProp;
11372 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11373 // paths through the function. This should be revisited if
11374 // -Wrepeated-use-of-weak is made flow-sensitive.
11375 if (FunctionScopeInfo *FSI = getCurFunction())
11376 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11377 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11378 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11379 Init->getBeginLoc()))
11380 FSI->markSafeWeakUse(Init);
11381 }
11382
11383 // The initialization is usually a full-expression.
11384 //
11385 // FIXME: If this is a braced initialization of an aggregate, it is not
11386 // an expression, and each individual field initializer is a separate
11387 // full-expression. For instance, in:
11388 //
11389 // struct Temp { ~Temp(); };
11390 // struct S { S(Temp); };
11391 // struct T { S a, b; } t = { Temp(), Temp() }
11392 //
11393 // we should destroy the first Temp before constructing the second.
11394 ExprResult Result =
11395 ActOnFinishFullExpr(Init, VDecl->getLocation(),
11396 /*DiscardedValue*/ false, VDecl->isConstexpr());
11397 if (Result.isInvalid()) {
11398 VDecl->setInvalidDecl();
11399 return;
11400 }
11401 Init = Result.get();
11402
11403 // Attach the initializer to the decl.
11404 VDecl->setInit(Init);
11405
11406 if (VDecl->isLocalVarDecl()) {
11407 // Don't check the initializer if the declaration is malformed.
11408 if (VDecl->isInvalidDecl()) {
11409 // do nothing
11410
11411 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11412 // This is true even in OpenCL C++.
11413 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11414 CheckForConstantInitializer(Init, DclT);
11415
11416 // Otherwise, C++ does not restrict the initializer.
11417 } else if (getLangOpts().CPlusPlus) {
11418 // do nothing
11419
11420 // C99 6.7.8p4: All the expressions in an initializer for an object that has
11421 // static storage duration shall be constant expressions or string literals.
11422 } else if (VDecl->getStorageClass() == SC_Static) {
11423 CheckForConstantInitializer(Init, DclT);
11424
11425 // C89 is stricter than C99 for aggregate initializers.
11426 // C89 6.5.7p3: All the expressions [...] in an initializer list
11427 // for an object that has aggregate or union type shall be
11428 // constant expressions.
11429 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11430 isa<InitListExpr>(Init)) {
11431 const Expr *Culprit;
11432 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11433 Diag(Culprit->getExprLoc(),
11434 diag::ext_aggregate_init_not_constant)
11435 << Culprit->getSourceRange();
11436 }
11437 }
11438
11439 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11440 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11441 if (VDecl->hasLocalStorage())
11442 BE->getBlockDecl()->setCanAvoidCopyToHeap();
11443 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11444 VDecl->getLexicalDeclContext()->isRecord()) {
11445 // This is an in-class initialization for a static data member, e.g.,
11446 //
11447 // struct S {
11448 // static const int value = 17;
11449 // };
11450
11451 // C++ [class.mem]p4:
11452 // A member-declarator can contain a constant-initializer only
11453 // if it declares a static member (9.4) of const integral or
11454 // const enumeration type, see 9.4.2.
11455 //
11456 // C++11 [class.static.data]p3:
11457 // If a non-volatile non-inline const static data member is of integral
11458 // or enumeration type, its declaration in the class definition can
11459 // specify a brace-or-equal-initializer in which every initializer-clause
11460 // that is an assignment-expression is a constant expression. A static
11461 // data member of literal type can be declared in the class definition
11462 // with the constexpr specifier; if so, its declaration shall specify a
11463 // brace-or-equal-initializer in which every initializer-clause that is
11464 // an assignment-expression is a constant expression.
11465
11466 // Do nothing on dependent types.
11467 if (DclT->isDependentType()) {
11468
11469 // Allow any 'static constexpr' members, whether or not they are of literal
11470 // type. We separately check that every constexpr variable is of literal
11471 // type.
11472 } else if (VDecl->isConstexpr()) {
11473
11474 // Require constness.
11475 } else if (!DclT.isConstQualified()) {
11476 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11477 << Init->getSourceRange();
11478 VDecl->setInvalidDecl();
11479
11480 // We allow integer constant expressions in all cases.
11481 } else if (DclT->isIntegralOrEnumerationType()) {
11482 // Check whether the expression is a constant expression.
11483 SourceLocation Loc;
11484 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11485 // In C++11, a non-constexpr const static data member with an
11486 // in-class initializer cannot be volatile.
11487 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11488 else if (Init->isValueDependent())
11489 ; // Nothing to check.
11490 else if (Init->isIntegerConstantExpr(Context, &Loc))
11491 ; // Ok, it's an ICE!
11492 else if (Init->getType()->isScopedEnumeralType() &&
11493 Init->isCXX11ConstantExpr(Context))
11494 ; // Ok, it is a scoped-enum constant expression.
11495 else if (Init->isEvaluatable(Context)) {
11496 // If we can constant fold the initializer through heroics, accept it,
11497 // but report this as a use of an extension for -pedantic.
11498 Diag(Loc, diag::ext_in_class_initializer_non_constant)
11499 << Init->getSourceRange();
11500 } else {
11501 // Otherwise, this is some crazy unknown case. Report the issue at the
11502 // location provided by the isIntegerConstantExpr failed check.
11503 Diag(Loc, diag::err_in_class_initializer_non_constant)
11504 << Init->getSourceRange();
11505 VDecl->setInvalidDecl();
11506 }
11507
11508 // We allow foldable floating-point constants as an extension.
11509 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11510 // In C++98, this is a GNU extension. In C++11, it is not, but we support
11511 // it anyway and provide a fixit to add the 'constexpr'.
11512 if (getLangOpts().CPlusPlus11) {
11513 Diag(VDecl->getLocation(),
11514 diag::ext_in_class_initializer_float_type_cxx11)
11515 << DclT << Init->getSourceRange();
11516 Diag(VDecl->getBeginLoc(),
11517 diag::note_in_class_initializer_float_type_cxx11)
11518 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11519 } else {
11520 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11521 << DclT << Init->getSourceRange();
11522
11523 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11524 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11525 << Init->getSourceRange();
11526 VDecl->setInvalidDecl();
11527 }
11528 }
11529
11530 // Suggest adding 'constexpr' in C++11 for literal types.
11531 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11532 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11533 << DclT << Init->getSourceRange()
11534 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11535 VDecl->setConstexpr(true);
11536
11537 } else {
11538 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11539 << DclT << Init->getSourceRange();
11540 VDecl->setInvalidDecl();
11541 }
11542 } else if (VDecl->isFileVarDecl()) {
11543 // In C, extern is typically used to avoid tentative definitions when
11544 // declaring variables in headers, but adding an intializer makes it a
11545 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11546 // In C++, extern is often used to give implictly static const variables
11547 // external linkage, so don't warn in that case. If selectany is present,
11548 // this might be header code intended for C and C++ inclusion, so apply the
11549 // C++ rules.
11550 if (VDecl->getStorageClass() == SC_Extern &&
11551 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11552 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11553 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11554 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11555 Diag(VDecl->getLocation(), diag::warn_extern_init);
11556
11557 // In Microsoft C++ mode, a const variable defined in namespace scope has
11558 // external linkage by default if the variable is declared with
11559 // __declspec(dllexport).
11560 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11561 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11562 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11563 VDecl->setStorageClass(SC_Extern);
11564
11565 // C99 6.7.8p4. All file scoped initializers need to be constant.
11566 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11567 CheckForConstantInitializer(Init, DclT);
11568 }
11569
11570 // We will represent direct-initialization similarly to copy-initialization:
11571 // int x(1); -as-> int x = 1;
11572 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11573 //
11574 // Clients that want to distinguish between the two forms, can check for
11575 // direct initializer using VarDecl::getInitStyle().
11576 // A major benefit is that clients that don't particularly care about which
11577 // exactly form was it (like the CodeGen) can handle both cases without
11578 // special case code.
11579
11580 // C++ 8.5p11:
11581 // The form of initialization (using parentheses or '=') is generally
11582 // insignificant, but does matter when the entity being initialized has a
11583 // class type.
11584 if (CXXDirectInit) {
11585 assert(DirectInit && "Call-style initializer must be direct init.");
11586 VDecl->setInitStyle(VarDecl::CallInit);
11587 } else if (DirectInit) {
11588 // This must be list-initialization. No other way is direct-initialization.
11589 VDecl->setInitStyle(VarDecl::ListInit);
11590 }
11591
11592 CheckCompleteVariableDeclaration(VDecl);
11593}
11594
11595/// ActOnInitializerError - Given that there was an error parsing an
11596/// initializer for the given declaration, try to return to some form
11597/// of sanity.
11598void Sema::ActOnInitializerError(Decl *D) {
11599 // Our main concern here is re-establishing invariants like "a
11600 // variable's type is either dependent or complete".
11601 if (!D || D->isInvalidDecl()) return;
11602
11603 VarDecl *VD = dyn_cast<VarDecl>(D);
11604 if (!VD) return;
11605
11606 // Bindings are not usable if we can't make sense of the initializer.
11607 if (auto *DD = dyn_cast<DecompositionDecl>(D))
11608 for (auto *BD : DD->bindings())
11609 BD->setInvalidDecl();
11610
11611 // Auto types are meaningless if we can't make sense of the initializer.
11612 if (ParsingInitForAutoVars.count(D)) {
11613 D->setInvalidDecl();
11614 return;
11615 }
11616
11617 QualType Ty = VD->getType();
11618 if (Ty->isDependentType()) return;
11619
11620 // Require a complete type.
11621 if (RequireCompleteType(VD->getLocation(),
11622 Context.getBaseElementType(Ty),
11623 diag::err_typecheck_decl_incomplete_type)) {
11624 VD->setInvalidDecl();
11625 return;
11626 }
11627
11628 // Require a non-abstract type.
11629 if (RequireNonAbstractType(VD->getLocation(), Ty,
11630 diag::err_abstract_type_in_decl,
11631 AbstractVariableType)) {
11632 VD->setInvalidDecl();
11633 return;
11634 }
11635
11636 // Don't bother complaining about constructors or destructors,
11637 // though.
11638}
11639
11640void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11641 // If there is no declaration, there was an error parsing it. Just ignore it.
11642 if (!RealDecl)
11643 return;
11644
11645 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11646 QualType Type = Var->getType();
11647
11648 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11649 if (isa<DecompositionDecl>(RealDecl)) {
11650 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11651 Var->setInvalidDecl();
11652 return;
11653 }
11654
11655 if (Type->isUndeducedType() &&
11656 DeduceVariableDeclarationType(Var, false, nullptr))
11657 return;
11658
11659 // C++11 [class.static.data]p3: A static data member can be declared with
11660 // the constexpr specifier; if so, its declaration shall specify
11661 // a brace-or-equal-initializer.
11662 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11663 // the definition of a variable [...] or the declaration of a static data
11664 // member.
11665 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11666 !Var->isThisDeclarationADemotedDefinition()) {
11667 if (Var->isStaticDataMember()) {
11668 // C++1z removes the relevant rule; the in-class declaration is always
11669 // a definition there.
11670 if (!getLangOpts().CPlusPlus17) {
11671 Diag(Var->getLocation(),
11672 diag::err_constexpr_static_mem_var_requires_init)
11673 << Var->getDeclName();
11674 Var->setInvalidDecl();
11675 return;
11676 }
11677 } else {
11678 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11679 Var->setInvalidDecl();
11680 return;
11681 }
11682 }
11683
11684 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11685 // be initialized.
11686 if (!Var->isInvalidDecl() &&
11687 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11688 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11689 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11690 Var->setInvalidDecl();
11691 return;
11692 }
11693
11694 switch (Var->isThisDeclarationADefinition()) {
11695 case VarDecl::Definition:
11696 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11697 break;
11698
11699 // We have an out-of-line definition of a static data member
11700 // that has an in-class initializer, so we type-check this like
11701 // a declaration.
11702 //
11703 LLVM_FALLTHROUGH;
11704
11705 case VarDecl::DeclarationOnly:
11706 // It's only a declaration.
11707
11708 // Block scope. C99 6.7p7: If an identifier for an object is
11709 // declared with no linkage (C99 6.2.2p6), the type for the
11710 // object shall be complete.
11711 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11712 !Var->hasLinkage() && !Var->isInvalidDecl() &&
11713 RequireCompleteType(Var->getLocation(), Type,
11714 diag::err_typecheck_decl_incomplete_type))
11715 Var->setInvalidDecl();
11716
11717 // Make sure that the type is not abstract.
11718 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11719 RequireNonAbstractType(Var->getLocation(), Type,
11720 diag::err_abstract_type_in_decl,
11721 AbstractVariableType))
11722 Var->setInvalidDecl();
11723 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11724 Var->getStorageClass() == SC_PrivateExtern) {
11725 Diag(Var->getLocation(), diag::warn_private_extern);
11726 Diag(Var->getLocation(), diag::note_private_extern);
11727 }
11728
11729 return;
11730
11731 case VarDecl::TentativeDefinition:
11732 // File scope. C99 6.9.2p2: A declaration of an identifier for an
11733 // object that has file scope without an initializer, and without a
11734 // storage-class specifier or with the storage-class specifier "static",
11735 // constitutes a tentative definition. Note: A tentative definition with
11736 // external linkage is valid (C99 6.2.2p5).
11737 if (!Var->isInvalidDecl()) {
11738 if (const IncompleteArrayType *ArrayT
11739 = Context.getAsIncompleteArrayType(Type)) {
11740 if (RequireCompleteType(Var->getLocation(),
11741 ArrayT->getElementType(),
11742 diag::err_illegal_decl_array_incomplete_type))
11743 Var->setInvalidDecl();
11744 } else if (Var->getStorageClass() == SC_Static) {
11745 // C99 6.9.2p3: If the declaration of an identifier for an object is
11746 // a tentative definition and has internal linkage (C99 6.2.2p3), the
11747 // declared type shall not be an incomplete type.
11748 // NOTE: code such as the following
11749 // static struct s;
11750 // struct s { int a; };
11751 // is accepted by gcc. Hence here we issue a warning instead of
11752 // an error and we do not invalidate the static declaration.
11753 // NOTE: to avoid multiple warnings, only check the first declaration.
11754 if (Var->isFirstDecl())
11755 RequireCompleteType(Var->getLocation(), Type,
11756 diag::ext_typecheck_decl_incomplete_type);
11757 }
11758 }
11759
11760 // Record the tentative definition; we're done.
11761 if (!Var->isInvalidDecl())
11762 TentativeDefinitions.push_back(Var);
11763 return;
11764 }
11765
11766 // Provide a specific diagnostic for uninitialized variable
11767 // definitions with incomplete array type.
11768 if (Type->isIncompleteArrayType()) {
11769 Diag(Var->getLocation(),
11770 diag::err_typecheck_incomplete_array_needs_initializer);
11771 Var->setInvalidDecl();
11772 return;
11773 }
11774
11775 // Provide a specific diagnostic for uninitialized variable
11776 // definitions with reference type.
11777 if (Type->isReferenceType()) {
11778 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11779 << Var->getDeclName()
11780 << SourceRange(Var->getLocation(), Var->getLocation());
11781 Var->setInvalidDecl();
11782 return;
11783 }
11784
11785 // Do not attempt to type-check the default initializer for a
11786 // variable with dependent type.
11787 if (Type->isDependentType())
11788 return;
11789
11790 if (Var->isInvalidDecl())
11791 return;
11792
11793 if (!Var->hasAttr<AliasAttr>()) {
11794 if (RequireCompleteType(Var->getLocation(),
11795 Context.getBaseElementType(Type),
11796 diag::err_typecheck_decl_incomplete_type)) {
11797 Var->setInvalidDecl();
11798 return;
11799 }
11800 } else {
11801 return;
11802 }
11803
11804 // The variable can not have an abstract class type.
11805 if (RequireNonAbstractType(Var->getLocation(), Type,
11806 diag::err_abstract_type_in_decl,
11807 AbstractVariableType)) {
11808 Var->setInvalidDecl();
11809 return;
11810 }
11811
11812 // Check for jumps past the implicit initializer. C++0x
11813 // clarifies that this applies to a "variable with automatic
11814 // storage duration", not a "local variable".
11815 // C++11 [stmt.dcl]p3
11816 // A program that jumps from a point where a variable with automatic
11817 // storage duration is not in scope to a point where it is in scope is
11818 // ill-formed unless the variable has scalar type, class type with a
11819 // trivial default constructor and a trivial destructor, a cv-qualified
11820 // version of one of these types, or an array of one of the preceding
11821 // types and is declared without an initializer.
11822 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11823 if (const RecordType *Record
11824 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11825 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11826 // Mark the function (if we're in one) for further checking even if the
11827 // looser rules of C++11 do not require such checks, so that we can
11828 // diagnose incompatibilities with C++98.
11829 if (!CXXRecord->isPOD())
11830 setFunctionHasBranchProtectedScope();
11831 }
11832 }
11833 // In OpenCL, we can't initialize objects in the __local address space,
11834 // even implicitly, so don't synthesize an implicit initializer.
11835 if (getLangOpts().OpenCL &&
11836 Var->getType().getAddressSpace() == LangAS::opencl_local)
11837 return;
11838 // C++03 [dcl.init]p9:
11839 // If no initializer is specified for an object, and the
11840 // object is of (possibly cv-qualified) non-POD class type (or
11841 // array thereof), the object shall be default-initialized; if
11842 // the object is of const-qualified type, the underlying class
11843 // type shall have a user-declared default
11844 // constructor. Otherwise, if no initializer is specified for
11845 // a non- static object, the object and its subobjects, if
11846 // any, have an indeterminate initial value); if the object
11847 // or any of its subobjects are of const-qualified type, the
11848 // program is ill-formed.
11849 // C++0x [dcl.init]p11:
11850 // If no initializer is specified for an object, the object is
11851 // default-initialized; [...].
11852 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11853 InitializationKind Kind
11854 = InitializationKind::CreateDefault(Var->getLocation());
11855
11856 InitializationSequence InitSeq(*this, Entity, Kind, None);
11857 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11858 if (Init.isInvalid())
11859 Var->setInvalidDecl();
11860 else if (Init.get()) {
11861 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11862 // This is important for template substitution.
11863 Var->setInitStyle(VarDecl::CallInit);
11864 }
11865
11866 CheckCompleteVariableDeclaration(Var);
11867 }
11868}
11869
11870void Sema::ActOnCXXForRangeDecl(Decl *D) {
11871 // If there is no declaration, there was an error parsing it. Ignore it.
11872 if (!D)
11873 return;
11874
11875 VarDecl *VD = dyn_cast<VarDecl>(D);
11876 if (!VD) {
11877 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11878 D->setInvalidDecl();
11879 return;
11880 }
11881
11882 VD->setCXXForRangeDecl(true);
11883
11884 // for-range-declaration cannot be given a storage class specifier.
11885 int Error = -1;
11886 switch (VD->getStorageClass()) {
11887 case SC_None:
11888 break;
11889 case SC_Extern:
11890 Error = 0;
11891 break;
11892 case SC_Static:
11893 Error = 1;
11894 break;
11895 case SC_PrivateExtern:
11896 Error = 2;
11897 break;
11898 case SC_Auto:
11899 Error = 3;
11900 break;
11901 case SC_Register:
11902 Error = 4;
11903 break;
11904 }
11905 if (Error != -1) {
11906 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11907 << VD->getDeclName() << Error;
11908 D->setInvalidDecl();
11909 }
11910}
11911
11912StmtResult
11913Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11914 IdentifierInfo *Ident,
11915 ParsedAttributes &Attrs,
11916 SourceLocation AttrEnd) {
11917 // C++1y [stmt.iter]p1:
11918 // A range-based for statement of the form
11919 // for ( for-range-identifier : for-range-initializer ) statement
11920 // is equivalent to
11921 // for ( auto&& for-range-identifier : for-range-initializer ) statement
11922 DeclSpec DS(Attrs.getPool().getFactory());
11923
11924 const char *PrevSpec;
11925 unsigned DiagID;
11926 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11927 getPrintingPolicy());
11928
11929 Declarator D(DS, DeclaratorContext::ForContext);
11930 D.SetIdentifier(Ident, IdentLoc);
11931 D.takeAttributes(Attrs, AttrEnd);
11932
11933 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11934 IdentLoc);
11935 Decl *Var = ActOnDeclarator(S, D);
11936 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11937 FinalizeDeclaration(Var);
11938 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11939 AttrEnd.isValid() ? AttrEnd : IdentLoc);
11940}
11941
11942void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11943 if (var->isInvalidDecl()) return;
11944
11945 if (getLangOpts().OpenCL) {
11946 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11947 // initialiser
11948 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11949 !var->hasInit()) {
11950 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11951 << 1 /*Init*/;
11952 var->setInvalidDecl();
11953 return;
11954 }
11955 }
11956
11957 // In Objective-C, don't allow jumps past the implicit initialization of a
11958 // local retaining variable.
11959 if (getLangOpts().ObjC &&
11960 var->hasLocalStorage()) {
11961 switch (var->getType().getObjCLifetime()) {
11962 case Qualifiers::OCL_None:
11963 case Qualifiers::OCL_ExplicitNone:
11964 case Qualifiers::OCL_Autoreleasing:
11965 break;
11966
11967 case Qualifiers::OCL_Weak:
11968 case Qualifiers::OCL_Strong:
11969 setFunctionHasBranchProtectedScope();
11970 break;
11971 }
11972 }
11973
11974 if (var->hasLocalStorage() &&
11975 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11976 setFunctionHasBranchProtectedScope();
11977
11978 // Warn about externally-visible variables being defined without a
11979 // prior declaration. We only want to do this for global
11980 // declarations, but we also specifically need to avoid doing it for
11981 // class members because the linkage of an anonymous class can
11982 // change if it's later given a typedef name.
11983 if (var->isThisDeclarationADefinition() &&
11984 var->getDeclContext()->getRedeclContext()->isFileContext() &&
11985 var->isExternallyVisible() && var->hasLinkage() &&
11986 !var->isInline() && !var->getDescribedVarTemplate() &&
11987 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11988 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11989 var->getLocation())) {
11990 // Find a previous declaration that's not a definition.
11991 VarDecl *prev = var->getPreviousDecl();
11992 while (prev && prev->isThisDeclarationADefinition())
11993 prev = prev->getPreviousDecl();
11994
11995 if (!prev)
11996 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11997 }
11998
11999 // Cache the result of checking for constant initialization.
12000 Optional<bool> CacheHasConstInit;
12001 const Expr *CacheCulprit;
12002 auto checkConstInit = [&]() mutable {
12003 if (!CacheHasConstInit)
12004 CacheHasConstInit = var->getInit()->isConstantInitializer(
12005 Context, var->getType()->isReferenceType(), &CacheCulprit);
12006 return *CacheHasConstInit;
12007 };
12008
12009 if (var->getTLSKind() == VarDecl::TLS_Static) {
12010 if (var->getType().isDestructedType()) {
12011 // GNU C++98 edits for __thread, [basic.start.term]p3:
12012 // The type of an object with thread storage duration shall not
12013 // have a non-trivial destructor.
12014 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12015 if (getLangOpts().CPlusPlus11)
12016 Diag(var->getLocation(), diag::note_use_thread_local);
12017 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12018 if (!checkConstInit()) {
12019 // GNU C++98 edits for __thread, [basic.start.init]p4:
12020 // An object of thread storage duration shall not require dynamic
12021 // initialization.
12022 // FIXME: Need strict checking here.
12023 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12024 << CacheCulprit->getSourceRange();
12025 if (getLangOpts().CPlusPlus11)
12026 Diag(var->getLocation(), diag::note_use_thread_local);
12027 }
12028 }
12029 }
12030
12031 // Apply section attributes and pragmas to global variables.
12032 bool GlobalStorage = var->hasGlobalStorage();
12033 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12034 !inTemplateInstantiation()) {
12035 PragmaStack<StringLiteral *> *Stack = nullptr;
12036 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12037 if (var->getType().isConstQualified())
12038 Stack = &ConstSegStack;
12039 else if (!var->getInit()) {
12040 Stack = &BSSSegStack;
12041 SectionFlags |= ASTContext::PSF_Write;
12042 } else {
12043 Stack = &DataSegStack;
12044 SectionFlags |= ASTContext::PSF_Write;
12045 }
12046 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
12047 var->addAttr(SectionAttr::CreateImplicit(
12048 Context, SectionAttr::Declspec_allocate,
12049 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
12050 }
12051 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12052 if (UnifySection(SA->getName(), SectionFlags, var))
12053 var->dropAttr<SectionAttr>();
12054
12055 // Apply the init_seg attribute if this has an initializer. If the
12056 // initializer turns out to not be dynamic, we'll end up ignoring this
12057 // attribute.
12058 if (CurInitSeg && var->getInit())
12059 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12060 CurInitSegLoc));
12061 }
12062
12063 // All the following checks are C++ only.
12064 if (!getLangOpts().CPlusPlus) {
12065 // If this variable must be emitted, add it as an initializer for the
12066 // current module.
12067 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12068 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12069 return;
12070 }
12071
12072 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12073 CheckCompleteDecompositionDeclaration(DD);
12074
12075 QualType type = var->getType();
12076 if (type->isDependentType()) return;
12077
12078 if (var->hasAttr<BlocksAttr>())
12079 getCurFunction()->addByrefBlockVar(var);
12080
12081 Expr *Init = var->getInit();
12082 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12083 QualType baseType = Context.getBaseElementType(type);
12084
12085 if (Init && !Init->isValueDependent()) {
12086 if (var->isConstexpr()) {
12087 SmallVector<PartialDiagnosticAt, 8> Notes;
12088 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12089 SourceLocation DiagLoc = var->getLocation();
12090 // If the note doesn't add any useful information other than a source
12091 // location, fold it into the primary diagnostic.
12092 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12093 diag::note_invalid_subexpr_in_const_expr) {
12094 DiagLoc = Notes[0].first;
12095 Notes.clear();
12096 }
12097 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12098 << var << Init->getSourceRange();
12099 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12100 Diag(Notes[I].first, Notes[I].second);
12101 }
12102 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12103 // Check whether the initializer of a const variable of integral or
12104 // enumeration type is an ICE now, since we can't tell whether it was
12105 // initialized by a constant expression if we check later.
12106 var->checkInitIsICE();
12107 }
12108
12109 // Don't emit further diagnostics about constexpr globals since they
12110 // were just diagnosed.
12111 if (!var->isConstexpr() && GlobalStorage &&
12112 var->hasAttr<RequireConstantInitAttr>()) {
12113 // FIXME: Need strict checking in C++03 here.
12114 bool DiagErr = getLangOpts().CPlusPlus11
12115 ? !var->checkInitIsICE() : !checkConstInit();
12116 if (DiagErr) {
12117 auto attr = var->getAttr<RequireConstantInitAttr>();
12118 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12119 << Init->getSourceRange();
12120 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12121 << attr->getRange();
12122 if (getLangOpts().CPlusPlus11) {
12123 APValue Value;
12124 SmallVector<PartialDiagnosticAt, 8> Notes;
12125 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12126 for (auto &it : Notes)
12127 Diag(it.first, it.second);
12128 } else {
12129 Diag(CacheCulprit->getExprLoc(),
12130 diag::note_invalid_subexpr_in_const_expr)
12131 << CacheCulprit->getSourceRange();
12132 }
12133 }
12134 }
12135 else if (!var->isConstexpr() && IsGlobal &&
12136 !getDiagnostics().isIgnored(diag::warn_global_constructor,
12137 var->getLocation())) {
12138 // Warn about globals which don't have a constant initializer. Don't
12139 // warn about globals with a non-trivial destructor because we already
12140 // warned about them.
12141 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12142 if (!(RD && !RD->hasTrivialDestructor())) {
12143 if (!checkConstInit())
12144 Diag(var->getLocation(), diag::warn_global_constructor)
12145 << Init->getSourceRange();
12146 }
12147 }
12148 }
12149
12150 // Require the destructor.
12151 if (const RecordType *recordType = baseType->getAs<RecordType>())
12152 FinalizeVarWithDestructor(var, recordType);
12153
12154 // If this variable must be emitted, add it as an initializer for the current
12155 // module.
12156 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12157 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12158}
12159
12160/// Determines if a variable's alignment is dependent.
12161static bool hasDependentAlignment(VarDecl *VD) {
12162 if (VD->getType()->isDependentType())
12163 return true;
12164 for (auto *I : VD->specific_attrs<AlignedAttr>())
12165 if (I->isAlignmentDependent())
12166 return true;
12167 return false;
12168}
12169
12170/// Check if VD needs to be dllexport/dllimport due to being in a
12171/// dllexport/import function.
12172void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12173 assert(VD->isStaticLocal());
12174
12175 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12176
12177 // Find outermost function when VD is in lambda function.
12178 while (FD && !getDLLAttr(FD) &&
12179 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12180 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12181 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12182 }
12183
12184 if (!FD)
12185 return;
12186
12187 // Static locals inherit dll attributes from their function.
12188 if (Attr *A = getDLLAttr(FD)) {
12189 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12190 NewAttr->setInherited(true);
12191 VD->addAttr(NewAttr);
12192 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12193 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12194 getASTContext(),
12195 A->getSpellingListIndex());
12196 NewAttr->setInherited(true);
12197 VD->addAttr(NewAttr);
12198
12199 // Export this function to enforce exporting this static variable even
12200 // if it is not used in this compilation unit.
12201 if (!FD->hasAttr<DLLExportAttr>())
12202 FD->addAttr(NewAttr);
12203
12204 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12205 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12206 getASTContext(),
12207 A->getSpellingListIndex());
12208 NewAttr->setInherited(true);
12209 VD->addAttr(NewAttr);
12210 }
12211}
12212
12213/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12214/// any semantic actions necessary after any initializer has been attached.
12215void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12216 // Note that we are no longer parsing the initializer for this declaration.
12217 ParsingInitForAutoVars.erase(ThisDecl);
12218
12219 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12220 if (!VD)
12221 return;
12222
12223 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12224 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12225 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12226 if (PragmaClangBSSSection.Valid)
12227 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12228 PragmaClangBSSSection.SectionName,
12229 PragmaClangBSSSection.PragmaLocation));
12230 if (PragmaClangDataSection.Valid)
12231 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12232 PragmaClangDataSection.SectionName,
12233 PragmaClangDataSection.PragmaLocation));
12234 if (PragmaClangRodataSection.Valid)
12235 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12236 PragmaClangRodataSection.SectionName,
12237 PragmaClangRodataSection.PragmaLocation));
12238 }
12239
12240 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12241 for (auto *BD : DD->bindings()) {
12242 FinalizeDeclaration(BD);
12243 }
12244 }
12245
12246 checkAttributesAfterMerging(*this, *VD);
12247
12248 // Perform TLS alignment check here after attributes attached to the variable
12249 // which may affect the alignment have been processed. Only perform the check
12250 // if the target has a maximum TLS alignment (zero means no constraints).
12251 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12252 // Protect the check so that it's not performed on dependent types and
12253 // dependent alignments (we can't determine the alignment in that case).
12254 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12255 !VD->isInvalidDecl()) {
12256 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12257 if (Context.getDeclAlign(VD) > MaxAlignChars) {
12258 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12259 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12260 << (unsigned)MaxAlignChars.getQuantity();
12261 }
12262 }
12263 }
12264
12265 if (VD->isStaticLocal()) {
12266 CheckStaticLocalForDllExport(VD);
12267
12268 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12269 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12270 // function, only __shared__ variables or variables without any device
12271 // memory qualifiers may be declared with static storage class.
12272 // Note: It is unclear how a function-scope non-const static variable
12273 // without device memory qualifier is implemented, therefore only static
12274 // const variable without device memory qualifier is allowed.
12275 [&]() {
12276 if (!getLangOpts().CUDA)
12277 return;
12278 if (VD->hasAttr<CUDASharedAttr>())
12279 return;
12280 if (VD->getType().isConstQualified() &&
12281 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12282 return;
12283 if (CUDADiagIfDeviceCode(VD->getLocation(),
12284 diag::err_device_static_local_var)
12285 << CurrentCUDATarget())
12286 VD->setInvalidDecl();
12287 }();
12288 }
12289 }
12290
12291 // Perform check for initializers of device-side global variables.
12292 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12293 // 7.5). We must also apply the same checks to all __shared__
12294 // variables whether they are local or not. CUDA also allows
12295 // constant initializers for __constant__ and __device__ variables.
12296 if (getLangOpts().CUDA)
12297 checkAllowedCUDAInitializer(VD);
12298
12299 // Grab the dllimport or dllexport attribute off of the VarDecl.
12300 const InheritableAttr *DLLAttr = getDLLAttr(VD);
12301
12302 // Imported static data members cannot be defined out-of-line.
12303 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12304 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12305 VD->isThisDeclarationADefinition()) {
12306 // We allow definitions of dllimport class template static data members
12307 // with a warning.
12308 CXXRecordDecl *Context =
12309 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12310 bool IsClassTemplateMember =
12311 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12312 Context->getDescribedClassTemplate();
12313
12314 Diag(VD->getLocation(),
12315 IsClassTemplateMember
12316 ? diag::warn_attribute_dllimport_static_field_definition
12317 : diag::err_attribute_dllimport_static_field_definition);
12318 Diag(IA->getLocation(), diag::note_attribute);
12319 if (!IsClassTemplateMember)
12320 VD->setInvalidDecl();
12321 }
12322 }
12323
12324 // dllimport/dllexport variables cannot be thread local, their TLS index
12325 // isn't exported with the variable.
12326 if (DLLAttr && VD->getTLSKind()) {
12327 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12328 if (F && getDLLAttr(F)) {
12329 assert(VD->isStaticLocal());
12330 // But if this is a static local in a dlimport/dllexport function, the
12331 // function will never be inlined, which means the var would never be
12332 // imported, so having it marked import/export is safe.
12333 } else {
12334 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12335 << DLLAttr;
12336 VD->setInvalidDecl();
12337 }
12338 }
12339
12340 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12341 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12342 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12343 VD->dropAttr<UsedAttr>();
12344 }
12345 }
12346
12347 const DeclContext *DC = VD->getDeclContext();
12348 // If there's a #pragma GCC visibility in scope, and this isn't a class
12349 // member, set the visibility of this variable.
12350 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12351 AddPushedVisibilityAttribute(VD);
12352
12353 // FIXME: Warn on unused var template partial specializations.
12354 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12355 MarkUnusedFileScopedDecl(VD);
12356
12357 // Now we have parsed the initializer and can update the table of magic
12358 // tag values.
12359 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12360 !VD->getType()->isIntegralOrEnumerationType())
12361 return;
12362
12363 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12364 const Expr *MagicValueExpr = VD->getInit();
12365 if (!MagicValueExpr) {
12366 continue;
12367 }
12368 llvm::APSInt MagicValueInt;
12369 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12370 Diag(I->getRange().getBegin(),
12371 diag::err_type_tag_for_datatype_not_ice)
12372 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12373 continue;
12374 }
12375 if (MagicValueInt.getActiveBits() > 64) {
12376 Diag(I->getRange().getBegin(),
12377 diag::err_type_tag_for_datatype_too_large)
12378 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12379 continue;
12380 }
12381 uint64_t MagicValue = MagicValueInt.getZExtValue();
12382 RegisterTypeTagForDatatype(I->getArgumentKind(),
12383 MagicValue,
12384 I->getMatchingCType(),
12385 I->getLayoutCompatible(),
12386 I->getMustBeNull());
12387 }
12388}
12389
12390static bool hasDeducedAuto(DeclaratorDecl *DD) {
12391 auto *VD = dyn_cast<VarDecl>(DD);
12392 return VD && !VD->getType()->hasAutoForTrailingReturnType();
12393}
12394
12395Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12396 ArrayRef<Decl *> Group) {
12397 SmallVector<Decl*, 8> Decls;
12398
12399 if (DS.isTypeSpecOwned())
12400 Decls.push_back(DS.getRepAsDecl());
12401
12402 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12403 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12404 bool DiagnosedMultipleDecomps = false;
12405 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12406 bool DiagnosedNonDeducedAuto = false;
12407
12408 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12409 if (Decl *D = Group[i]) {
12410 // For declarators, there are some additional syntactic-ish checks we need
12411 // to perform.
12412 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12413 if (!FirstDeclaratorInGroup)
12414 FirstDeclaratorInGroup = DD;
12415 if (!FirstDecompDeclaratorInGroup)
12416 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12417 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12418 !hasDeducedAuto(DD))
12419 FirstNonDeducedAutoInGroup = DD;
12420
12421 if (FirstDeclaratorInGroup != DD) {
12422 // A decomposition declaration cannot be combined with any other
12423 // declaration in the same group.
12424 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12425 Diag(FirstDecompDeclaratorInGroup->getLocation(),
12426 diag::err_decomp_decl_not_alone)
12427 << FirstDeclaratorInGroup->getSourceRange()
12428 << DD->getSourceRange();
12429 DiagnosedMultipleDecomps = true;
12430 }
12431
12432 // A declarator that uses 'auto' in any way other than to declare a
12433 // variable with a deduced type cannot be combined with any other
12434 // declarator in the same group.
12435 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12436 Diag(FirstNonDeducedAutoInGroup->getLocation(),
12437 diag::err_auto_non_deduced_not_alone)
12438 << FirstNonDeducedAutoInGroup->getType()
12439 ->hasAutoForTrailingReturnType()
12440 << FirstDeclaratorInGroup->getSourceRange()
12441 << DD->getSourceRange();
12442 DiagnosedNonDeducedAuto = true;
12443 }
12444 }
12445 }
12446
12447 Decls.push_back(D);
12448 }
12449 }
12450
12451 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12452 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12453 handleTagNumbering(Tag, S);
12454 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12455 getLangOpts().CPlusPlus)
12456 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12457 }
12458 }
12459
12460 return BuildDeclaratorGroup(Decls);
12461}
12462
12463/// BuildDeclaratorGroup - convert a list of declarations into a declaration
12464/// group, performing any necessary semantic checking.
12465Sema::DeclGroupPtrTy
12466Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12467 // C++14 [dcl.spec.auto]p7: (DR1347)
12468 // If the type that replaces the placeholder type is not the same in each
12469 // deduction, the program is ill-formed.
12470 if (Group.size() > 1) {
12471 QualType Deduced;
12472 VarDecl *DeducedDecl = nullptr;
12473 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12474 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12475 if (!D || D->isInvalidDecl())
12476 break;
12477 DeducedType *DT = D->getType()->getContainedDeducedType();
12478 if (!DT || DT->getDeducedType().isNull())
12479 continue;
12480 if (Deduced.isNull()) {
12481 Deduced = DT->getDeducedType();
12482 DeducedDecl = D;
12483 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12484 auto *AT = dyn_cast<AutoType>(DT);
12485 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12486 diag::err_auto_different_deductions)
12487 << (AT ? (unsigned)AT->getKeyword() : 3)
12488 << Deduced << DeducedDecl->getDeclName()
12489 << DT->getDeducedType() << D->getDeclName()
12490 << DeducedDecl->getInit()->getSourceRange()
12491 << D->getInit()->getSourceRange();
12492 D->setInvalidDecl();
12493 break;
12494 }
12495 }
12496 }
12497
12498 ActOnDocumentableDecls(Group);
12499
12500 return DeclGroupPtrTy::make(
12501 DeclGroupRef::Create(Context, Group.data(), Group.size()));
12502}
12503
12504void Sema::ActOnDocumentableDecl(Decl *D) {
12505 ActOnDocumentableDecls(D);
12506}
12507
12508void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12509 // Don't parse the comment if Doxygen diagnostics are ignored.
12510 if (Group.empty() || !Group[0])
12511 return;
12512
12513 if (Diags.isIgnored(diag::warn_doc_param_not_found,
12514 Group[0]->getLocation()) &&
12515 Diags.isIgnored(diag::warn_unknown_comment_command_name,
12516 Group[0]->getLocation()))
12517 return;
12518
12519 if (Group.size() >= 2) {
12520 // This is a decl group. Normally it will contain only declarations
12521 // produced from declarator list. But in case we have any definitions or
12522 // additional declaration references:
12523 // 'typedef struct S {} S;'
12524 // 'typedef struct S *S;'
12525 // 'struct S *pS;'
12526 // FinalizeDeclaratorGroup adds these as separate declarations.
12527 Decl *MaybeTagDecl = Group[0];
12528 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12529 Group = Group.slice(1);
12530 }
12531 }
12532
12533 // See if there are any new comments that are not attached to a decl.
12534 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12535 if (!Comments.empty() &&
12536 !Comments.back()->isAttached()) {
12537 // There is at least one comment that not attached to a decl.
12538 // Maybe it should be attached to one of these decls?
12539 //
12540 // Note that this way we pick up not only comments that precede the
12541 // declaration, but also comments that *follow* the declaration -- thanks to
12542 // the lookahead in the lexer: we've consumed the semicolon and looked
12543 // ahead through comments.
12544 for (unsigned i = 0, e = Group.size(); i != e; ++i)
12545 Context.getCommentForDecl(Group[i], &PP);
12546 }
12547}
12548
12549/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12550/// to introduce parameters into function prototype scope.
12551Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12552 const DeclSpec &DS = D.getDeclSpec();
12553
12554 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12555
12556 // C++03 [dcl.stc]p2 also permits 'auto'.
12557 StorageClass SC = SC_None;
12558 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12559 SC = SC_Register;
12560 // In C++11, the 'register' storage class specifier is deprecated.
12561 // In C++17, it is not allowed, but we tolerate it as an extension.
12562 if (getLangOpts().CPlusPlus11) {
12563 Diag(DS.getStorageClassSpecLoc(),
12564 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12565 : diag::warn_deprecated_register)
12566 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12567 }
12568 } else if (getLangOpts().CPlusPlus &&
12569 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12570 SC = SC_Auto;
12571 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12572 Diag(DS.getStorageClassSpecLoc(),
12573 diag::err_invalid_storage_class_in_func_decl);
12574 D.getMutableDeclSpec().ClearStorageClassSpecs();
12575 }
12576
12577 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12578 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12579 << DeclSpec::getSpecifierName(TSCS);
12580 if (DS.isInlineSpecified())
12581 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12582 << getLangOpts().CPlusPlus17;
12583 if (DS.isConstexprSpecified())
12584 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12585 << 0;
12586
12587 DiagnoseFunctionSpecifiers(DS);
12588
12589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12590 QualType parmDeclType = TInfo->getType();
12591
12592 if (getLangOpts().CPlusPlus) {
12593 // Check that there are no default arguments inside the type of this
12594 // parameter.
12595 CheckExtraCXXDefaultArguments(D);
12596
12597 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12598 if (D.getCXXScopeSpec().isSet()) {
12599 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12600 << D.getCXXScopeSpec().getRange();
12601 D.getCXXScopeSpec().clear();
12602 }
12603 }
12604
12605 // Ensure we have a valid name
12606 IdentifierInfo *II = nullptr;
12607 if (D.hasName()) {
12608 II = D.getIdentifier();
12609 if (!II) {
12610 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12611 << GetNameForDeclarator(D).getName();
12612 D.setInvalidType(true);
12613 }
12614 }
12615
12616 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12617 if (II) {
12618 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12619 ForVisibleRedeclaration);
12620 LookupName(R, S);
12621 if (R.isSingleResult()) {
12622 NamedDecl *PrevDecl = R.getFoundDecl();
12623 if (PrevDecl->isTemplateParameter()) {
12624 // Maybe we will complain about the shadowed template parameter.
12625 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12626 // Just pretend that we didn't see the previous declaration.
12627 PrevDecl = nullptr;
12628 } else if (S->isDeclScope(PrevDecl)) {
12629 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12630 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12631
12632 // Recover by removing the name
12633 II = nullptr;
12634 D.SetIdentifier(nullptr, D.getIdentifierLoc());
12635 D.setInvalidType(true);
12636 }
12637 }
12638 }
12639
12640 // Temporarily put parameter variables in the translation unit, not
12641 // the enclosing context. This prevents them from accidentally
12642 // looking like class members in C++.
12643 ParmVarDecl *New =
12644 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12645 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12646
12647 if (D.isInvalidType())
12648 New->setInvalidDecl();
12649
12650 assert(S->isFunctionPrototypeScope());
12651 assert(S->getFunctionPrototypeDepth() >= 1);
12652 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12653 S->getNextFunctionPrototypeIndex());
12654
12655 // Add the parameter declaration into this scope.
12656 S->AddDecl(New);
12657 if (II)
12658 IdResolver.AddDecl(New);
12659
12660 ProcessDeclAttributes(S, New, D);
12661
12662 if (D.getDeclSpec().isModulePrivateSpecified())
12663 Diag(New->getLocation(), diag::err_module_private_local)
12664 << 1 << New->getDeclName()
12665 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12666 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12667
12668 if (New->hasAttr<BlocksAttr>()) {
12669 Diag(New->getLocation(), diag::err_block_on_nonlocal);
12670 }
12671 return New;
12672}
12673
12674/// Synthesizes a variable for a parameter arising from a
12675/// typedef.
12676ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12677 SourceLocation Loc,
12678 QualType T) {
12679 /* FIXME: setting StartLoc == Loc.
12680 Would it be worth to modify callers so as to provide proper source
12681 location for the unnamed parameters, embedding the parameter's type? */
12682 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12683 T, Context.getTrivialTypeSourceInfo(T, Loc),
12684 SC_None, nullptr);
12685 Param->setImplicit();
12686 return Param;
12687}
12688
12689void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12690 // Don't diagnose unused-parameter errors in template instantiations; we
12691 // will already have done so in the template itself.
12692 if (inTemplateInstantiation())
12693 return;
12694
12695 for (const ParmVarDecl *Parameter : Parameters) {
12696 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12697 !Parameter->hasAttr<UnusedAttr>()) {
12698 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12699 << Parameter->getDeclName();
12700 }
12701 }
12702}
12703
12704void Sema::DiagnoseSizeOfParametersAndReturnValue(
12705 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12706 if (LangOpts.NumLargeByValueCopy == 0) // No check.
12707 return;
12708
12709 // Warn if the return value is pass-by-value and larger than the specified
12710 // threshold.
12711 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12712 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12713 if (Size > LangOpts.NumLargeByValueCopy)
12714 Diag(D->getLocation(), diag::warn_return_value_size)
12715 << D->getDeclName() << Size;
12716 }
12717
12718 // Warn if any parameter is pass-by-value and larger than the specified
12719 // threshold.
12720 for (const ParmVarDecl *Parameter : Parameters) {
12721 QualType T = Parameter->getType();
12722 if (T->isDependentType() || !T.isPODType(Context))
12723 continue;
12724 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12725 if (Size > LangOpts.NumLargeByValueCopy)
12726 Diag(Parameter->getLocation(), diag::warn_parameter_size)
12727 << Parameter->getDeclName() << Size;
12728 }
12729}
12730
12731ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12732 SourceLocation NameLoc, IdentifierInfo *Name,
12733 QualType T, TypeSourceInfo *TSInfo,
12734 StorageClass SC) {
12735 // In ARC, infer a lifetime qualifier for appropriate parameter types.
12736 if (getLangOpts().ObjCAutoRefCount &&
12737 T.getObjCLifetime() == Qualifiers::OCL_None &&
12738 T->isObjCLifetimeType()) {
12739
12740 Qualifiers::ObjCLifetime lifetime;
12741
12742 // Special cases for arrays:
12743 // - if it's const, use __unsafe_unretained
12744 // - otherwise, it's an error
12745 if (T->isArrayType()) {
12746 if (!T.isConstQualified()) {
12747 if (DelayedDiagnostics.shouldDelayDiagnostics())
12748 DelayedDiagnostics.add(
12749 sema::DelayedDiagnostic::makeForbiddenType(
12750 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12751 else
12752 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12753 << TSInfo->getTypeLoc().getSourceRange();
12754 }
12755 lifetime = Qualifiers::OCL_ExplicitNone;
12756 } else {
12757 lifetime = T->getObjCARCImplicitLifetime();
12758 }
12759 T = Context.getLifetimeQualifiedType(T, lifetime);
12760 }
12761
12762 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12763 Context.getAdjustedParameterType(T),
12764 TSInfo, SC, nullptr);
12765
12766 // Parameters can not be abstract class types.
12767 // For record types, this is done by the AbstractClassUsageDiagnoser once
12768 // the class has been completely parsed.
12769 if (!CurContext->isRecord() &&
12770 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12771 AbstractParamType))
12772 New->setInvalidDecl();
12773
12774 // Parameter declarators cannot be interface types. All ObjC objects are
12775 // passed by reference.
12776 if (T->isObjCObjectType()) {
12777 SourceLocation TypeEndLoc =
12778 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12779 Diag(NameLoc,
12780 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12781 << FixItHint::CreateInsertion(TypeEndLoc, "*");
12782 T = Context.getObjCObjectPointerType(T);
12783 New->setType(T);
12784 }
12785
12786 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12787 // duration shall not be qualified by an address-space qualifier."
12788 // Since all parameters have automatic store duration, they can not have
12789 // an address space.
12790 if (T.getAddressSpace() != LangAS::Default &&
12791 // OpenCL allows function arguments declared to be an array of a type
12792 // to be qualified with an address space.
12793 !(getLangOpts().OpenCL &&
12794 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12795 Diag(NameLoc, diag::err_arg_with_address_space);
12796 New->setInvalidDecl();
12797 }
12798
12799 return New;
12800}
12801
12802void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12803 SourceLocation LocAfterDecls) {
12804 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12805
12806 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12807 // for a K&R function.
12808 if (!FTI.hasPrototype) {
12809 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12810 --i;
12811 if (FTI.Params[i].Param == nullptr) {
12812 SmallString<256> Code;
12813 llvm::raw_svector_ostream(Code)
12814 << " int " << FTI.Params[i].Ident->getName() << ";\n";
12815 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12816 << FTI.Params[i].Ident
12817 << FixItHint::CreateInsertion(LocAfterDecls, Code);
12818
12819 // Implicitly declare the argument as type 'int' for lack of a better
12820 // type.
12821 AttributeFactory attrs;
12822 DeclSpec DS(attrs);
12823 const char* PrevSpec; // unused
12824 unsigned DiagID; // unused
12825 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12826 DiagID, Context.getPrintingPolicy());
12827 // Use the identifier location for the type source range.
12828 DS.SetRangeStart(FTI.Params[i].IdentLoc);
12829 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12830 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12831 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12832 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12833 }
12834 }
12835 }
12836}
12837
12838Decl *
12839Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12840 MultiTemplateParamsArg TemplateParameterLists,
12841 SkipBodyInfo *SkipBody) {
12842 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12843 assert(D.isFunctionDeclarator() && "Not a function declarator!");
12844 Scope *ParentScope = FnBodyScope->getParent();
12845
12846 D.setFunctionDefinitionKind(FDK_Definition);
12847 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12848 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12849}
12850
12851void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12852 Consumer.HandleInlineFunctionDefinition(D);
12853}
12854
12855static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12856 const FunctionDecl*& PossibleZeroParamPrototype) {
12857 // Don't warn about invalid declarations.
12858 if (FD->isInvalidDecl())
12859 return false;
12860
12861 // Or declarations that aren't global.
12862 if (!FD->isGlobal())
12863 return false;
12864
12865 // Don't warn about C++ member functions.
12866 if (isa<CXXMethodDecl>(FD))
12867 return false;
12868
12869 // Don't warn about 'main'.
12870 if (FD->isMain())
12871 return false;
12872
12873 // Don't warn about inline functions.
12874 if (FD->isInlined())
12875 return false;
12876
12877 // Don't warn about function templates.
12878 if (FD->getDescribedFunctionTemplate())
12879 return false;
12880
12881 // Don't warn about function template specializations.
12882 if (FD->isFunctionTemplateSpecialization())
12883 return false;
12884
12885 // Don't warn for OpenCL kernels.
12886 if (FD->hasAttr<OpenCLKernelAttr>())
12887 return false;
12888
12889 // Don't warn on explicitly deleted functions.
12890 if (FD->isDeleted())
12891 return false;
12892
12893 bool MissingPrototype = true;
12894 for (const FunctionDecl *Prev = FD->getPreviousDecl();
12895 Prev; Prev = Prev->getPreviousDecl()) {
12896 // Ignore any declarations that occur in function or method
12897 // scope, because they aren't visible from the header.
12898 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12899 continue;
12900
12901 MissingPrototype = !Prev->getType()->isFunctionProtoType();
12902 if (FD->getNumParams() == 0)
12903 PossibleZeroParamPrototype = Prev;
12904 break;
12905 }
12906
12907 return MissingPrototype;
12908}
12909
12910void
12911Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12912 const FunctionDecl *EffectiveDefinition,
12913 SkipBodyInfo *SkipBody) {
12914 const FunctionDecl *Definition = EffectiveDefinition;
12915 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12916 // If this is a friend function defined in a class template, it does not
12917 // have a body until it is used, nevertheless it is a definition, see
12918 // [temp.inst]p2:
12919 //
12920 // ... for the purpose of determining whether an instantiated redeclaration
12921 // is valid according to [basic.def.odr] and [class.mem], a declaration that
12922 // corresponds to a definition in the template is considered to be a
12923 // definition.
12924 //
12925 // The following code must produce redefinition error:
12926 //
12927 // template<typename T> struct C20 { friend void func_20() {} };
12928 // C20<int> c20i;
12929 // void func_20() {}
12930 //
12931 for (auto I : FD->redecls()) {
12932 if (I != FD && !I->isInvalidDecl() &&
12933 I->getFriendObjectKind() != Decl::FOK_None) {
12934 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12935 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12936 // A merged copy of the same function, instantiated as a member of
12937 // the same class, is OK.
12938 if (declaresSameEntity(OrigFD, Original) &&
12939 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12940 cast<Decl>(FD->getLexicalDeclContext())))
12941 continue;
12942 }
12943
12944 if (Original->isThisDeclarationADefinition()) {
12945 Definition = I;
12946 break;
12947 }
12948 }
12949 }
12950 }
12951 }
12952
12953 if (!Definition)
12954 // Similar to friend functions a friend function template may be a
12955 // definition and do not have a body if it is instantiated in a class
12956 // template.
12957 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12958 for (auto I : FTD->redecls()) {
12959 auto D = cast<FunctionTemplateDecl>(I);
12960 if (D != FTD) {
12961 assert(!D->isThisDeclarationADefinition() &&
12962 "More than one definition in redeclaration chain");
12963 if (D->getFriendObjectKind() != Decl::FOK_None)
12964 if (FunctionTemplateDecl *FT =
12965 D->getInstantiatedFromMemberTemplate()) {
12966 if (FT->isThisDeclarationADefinition()) {
12967 Definition = D->getTemplatedDecl();
12968 break;
12969 }
12970 }
12971 }
12972 }
12973 }
12974
12975 if (!Definition)
12976 return;
12977
12978 if (canRedefineFunction(Definition, getLangOpts()))
12979 return;
12980
12981 // Don't emit an error when this is redefinition of a typo-corrected
12982 // definition.
12983 if (TypoCorrectedFunctionDefinitions.count(Definition))
12984 return;
12985
12986 // If we don't have a visible definition of the function, and it's inline or
12987 // a template, skip the new definition.
12988 if (SkipBody && !hasVisibleDefinition(Definition) &&
12989 (Definition->getFormalLinkage() == InternalLinkage ||
12990 Definition->isInlined() ||
12991 Definition->getDescribedFunctionTemplate() ||
12992 Definition->getNumTemplateParameterLists())) {
12993 SkipBody->ShouldSkip = true;
12994 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12995 if (auto *TD = Definition->getDescribedFunctionTemplate())
12996 makeMergedDefinitionVisible(TD);
12997 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12998 return;
12999 }
13000
13001 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13002 Definition->getStorageClass() == SC_Extern)
13003 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13004 << FD->getDeclName() << getLangOpts().CPlusPlus;
13005 else
13006 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13007
13008 Diag(Definition->getLocation(), diag::note_previous_definition);
13009 FD->setInvalidDecl();
13010}
13011
13012static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13013 Sema &S) {
13014 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13015
13016 LambdaScopeInfo *LSI = S.PushLambdaScope();
13017 LSI->CallOperator = CallOperator;
13018 LSI->Lambda = LambdaClass;
13019 LSI->ReturnType = CallOperator->getReturnType();
13020 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13021
13022 if (LCD == LCD_None)
13023 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13024 else if (LCD == LCD_ByCopy)
13025 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13026 else if (LCD == LCD_ByRef)
13027 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13028 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13029
13030 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13031 LSI->Mutable = !CallOperator->isConst();
13032
13033 // Add the captures to the LSI so they can be noted as already
13034 // captured within tryCaptureVar.
13035 auto I = LambdaClass->field_begin();
13036 for (const auto &C : LambdaClass->captures()) {
13037 if (C.capturesVariable()) {
13038 VarDecl *VD = C.getCapturedVar();
13039 if (VD->isInitCapture())
13040 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13041 QualType CaptureType = VD->getType();
13042 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13043 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13044 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13045 /*EllipsisLoc*/C.isPackExpansion()
13046 ? C.getEllipsisLoc() : SourceLocation(),
13047 CaptureType, /*Invalid*/false);
13048
13049 } else if (C.capturesThis()) {
13050 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13051 C.getCaptureKind() == LCK_StarThis);
13052 } else {
13053 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13054 I->getType());
13055 }
13056 ++I;
13057 }
13058}
13059
13060Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13061 SkipBodyInfo *SkipBody) {
13062 if (!D) {
13063 // Parsing the function declaration failed in some way. Push on a fake scope
13064 // anyway so we can try to parse the function body.
13065 PushFunctionScope();
13066 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13067 return D;
13068 }
13069
13070 FunctionDecl *FD = nullptr;
13071
13072 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13073 FD = FunTmpl->getTemplatedDecl();
13074 else
13075 FD = cast<FunctionDecl>(D);
13076
13077 // Do not push if it is a lambda because one is already pushed when building
13078 // the lambda in ActOnStartOfLambdaDefinition().
13079 if (!isLambdaCallOperator(FD))
13080 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13081
13082 // Check for defining attributes before the check for redefinition.
13083 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13084 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13085 FD->dropAttr<AliasAttr>();
13086 FD->setInvalidDecl();
13087 }
13088 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13089 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13090 FD->dropAttr<IFuncAttr>();
13091 FD->setInvalidDecl();
13092 }
13093
13094 // See if this is a redefinition. If 'will have body' is already set, then
13095 // these checks were already performed when it was set.
13096 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13097 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13098
13099 // If we're skipping the body, we're done. Don't enter the scope.
13100 if (SkipBody && SkipBody->ShouldSkip)
13101 return D;
13102 }
13103
13104 // Mark this function as "will have a body eventually". This lets users to
13105 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13106 // this function.
13107 FD->setWillHaveBody();
13108
13109 // If we are instantiating a generic lambda call operator, push
13110 // a LambdaScopeInfo onto the function stack. But use the information
13111 // that's already been calculated (ActOnLambdaExpr) to prime the current
13112 // LambdaScopeInfo.
13113 // When the template operator is being specialized, the LambdaScopeInfo,
13114 // has to be properly restored so that tryCaptureVariable doesn't try
13115 // and capture any new variables. In addition when calculating potential
13116 // captures during transformation of nested lambdas, it is necessary to
13117 // have the LSI properly restored.
13118 if (isGenericLambdaCallOperatorSpecialization(FD)) {
13119 assert(inTemplateInstantiation() &&
13120 "There should be an active template instantiation on the stack "
13121 "when instantiating a generic lambda!");
13122 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13123 } else {
13124 // Enter a new function scope
13125 PushFunctionScope();
13126 }
13127
13128 // Builtin functions cannot be defined.
13129 if (unsigned BuiltinID = FD->getBuiltinID()) {
13130 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13131 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13132 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13133 FD->setInvalidDecl();
13134 }
13135 }
13136
13137 // The return type of a function definition must be complete
13138 // (C99 6.9.1p3, C++ [dcl.fct]p6).
13139 QualType ResultType = FD->getReturnType();
13140 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13141 !FD->isInvalidDecl() &&
13142 RequireCompleteType(FD->getLocation(), ResultType,
13143 diag::err_func_def_incomplete_result))
13144 FD->setInvalidDecl();
13145
13146 if (FnBodyScope)
13147 PushDeclContext(FnBodyScope, FD);
13148
13149 // Check the validity of our function parameters
13150 CheckParmsForFunctionDef(FD->parameters(),
13151 /*CheckParameterNames=*/true);
13152
13153 // Add non-parameter declarations already in the function to the current
13154 // scope.
13155 if (FnBodyScope) {
13156 for (Decl *NPD : FD->decls()) {
13157 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13158 if (!NonParmDecl)
13159 continue;
13160 assert(!isa<ParmVarDecl>(NonParmDecl) &&
13161 "parameters should not be in newly created FD yet");
13162
13163 // If the decl has a name, make it accessible in the current scope.
13164 if (NonParmDecl->getDeclName())
13165 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13166
13167 // Similarly, dive into enums and fish their constants out, making them
13168 // accessible in this scope.
13169 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13170 for (auto *EI : ED->enumerators())
13171 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13172 }
13173 }
13174 }
13175
13176 // Introduce our parameters into the function scope
13177 for (auto Param : FD->parameters()) {
13178 Param->setOwningFunction(FD);
13179
13180 // If this has an identifier, add it to the scope stack.
13181 if (Param->getIdentifier() && FnBodyScope) {
13182 CheckShadow(FnBodyScope, Param);
13183
13184 PushOnScopeChains(Param, FnBodyScope);
13185 }
13186 }
13187
13188 // Ensure that the function's exception specification is instantiated.
13189 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13190 ResolveExceptionSpec(D->getLocation(), FPT);
13191
13192 // dllimport cannot be applied to non-inline function definitions.
13193 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13194 !FD->isTemplateInstantiation()) {
13195 assert(!FD->hasAttr<DLLExportAttr>());
13196 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13197 FD->setInvalidDecl();
13198 return D;
13199 }
13200 // We want to attach documentation to original Decl (which might be
13201 // a function template).
13202 ActOnDocumentableDecl(D);
13203 if (getCurLexicalContext()->isObjCContainer() &&
13204 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13205 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13206 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13207
13208 return D;
13209}
13210
13211/// Given the set of return statements within a function body,
13212/// compute the variables that are subject to the named return value
13213/// optimization.
13214///
13215/// Each of the variables that is subject to the named return value
13216/// optimization will be marked as NRVO variables in the AST, and any
13217/// return statement that has a marked NRVO variable as its NRVO candidate can
13218/// use the named return value optimization.
13219///
13220/// This function applies a very simplistic algorithm for NRVO: if every return
13221/// statement in the scope of a variable has the same NRVO candidate, that
13222/// candidate is an NRVO variable.
13223void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13224 ReturnStmt **Returns = Scope->Returns.data();
13225
13226 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13227 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13228 if (!NRVOCandidate->isNRVOVariable())
13229 Returns[I]->setNRVOCandidate(nullptr);
13230 }
13231 }
13232}
13233
13234bool Sema::canDelayFunctionBody(const Declarator &D) {
13235 // We can't delay parsing the body of a constexpr function template (yet).
13236 if (D.getDeclSpec().isConstexprSpecified())
13237 return false;
13238
13239 // We can't delay parsing the body of a function template with a deduced
13240 // return type (yet).
13241 if (D.getDeclSpec().hasAutoTypeSpec()) {
13242 // If the placeholder introduces a non-deduced trailing return type,
13243 // we can still delay parsing it.
13244 if (D.getNumTypeObjects()) {
13245 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13246 if (Outer.Kind == DeclaratorChunk::Function &&
13247 Outer.Fun.hasTrailingReturnType()) {
13248 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13249 return Ty.isNull() || !Ty->isUndeducedType();
13250 }
13251 }
13252 return false;
13253 }
13254
13255 return true;
13256}
13257
13258bool Sema::canSkipFunctionBody(Decl *D) {
13259 // We cannot skip the body of a function (or function template) which is
13260 // constexpr, since we may need to evaluate its body in order to parse the
13261 // rest of the file.
13262 // We cannot skip the body of a function with an undeduced return type,
13263 // because any callers of that function need to know the type.
13264 if (const FunctionDecl *FD = D->getAsFunction()) {
13265 if (FD->isConstexpr())
13266 return false;
13267 // We can't simply call Type::isUndeducedType here, because inside template
13268 // auto can be deduced to a dependent type, which is not considered
13269 // "undeduced".
13270 if (FD->getReturnType()->getContainedDeducedType())
13271 return false;
13272 }
13273 return Consumer.shouldSkipFunctionBody(D);
13274}
13275
13276Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13277 if (!Decl)
13278 return nullptr;
13279 if (FunctionDecl *FD = Decl->getAsFunction())
13280 FD->setHasSkippedBody();
13281 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13282 MD->setHasSkippedBody();
13283 return Decl;
13284}
13285
13286Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13287 return ActOnFinishFunctionBody(D, BodyArg, false);
13288}
13289
13290/// RAII object that pops an ExpressionEvaluationContext when exiting a function
13291/// body.
13292class ExitFunctionBodyRAII {
13293public:
13294 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13295 ~ExitFunctionBodyRAII() {
13296 if (!IsLambda)
13297 S.PopExpressionEvaluationContext();
13298 }
13299
13300private:
13301 Sema &S;
13302 bool IsLambda = false;
13303};
13304
13305static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13306 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13307
13308 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13309 if (EscapeInfo.count(BD))
13310 return EscapeInfo[BD];
13311
13312 bool R = false;
13313 const BlockDecl *CurBD = BD;
13314
13315 do {
13316 R = !CurBD->doesNotEscape();
13317 if (R)
13318 break;
13319 CurBD = CurBD->getParent()->getInnermostBlockDecl();
13320 } while (CurBD);
13321
13322 return EscapeInfo[BD] = R;
13323 };
13324
13325 // If the location where 'self' is implicitly retained is inside a escaping
13326 // block, emit a diagnostic.
13327 for (const std::pair<SourceLocation, const BlockDecl *> &P :
13328 S.ImplicitlyRetainedSelfLocs)
13329 if (IsOrNestedInEscapingBlock(P.second))
13330 S.Diag(P.first, diag::warn_implicitly_retains_self)
13331 << FixItHint::CreateInsertion(P.first, "self->");
13332}
13333
13334Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13335 bool IsInstantiation) {
13336 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13337
13338 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13339 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13340
13341 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13342 CheckCompletedCoroutineBody(FD, Body);
13343
13344 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13345 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13346 // meant to pop the context added in ActOnStartOfFunctionDef().
13347 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13348
13349 if (FD) {
13350 FD->setBody(Body);
13351 FD->setWillHaveBody(false);
13352
13353 if (getLangOpts().CPlusPlus14) {
13354 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13355 FD->getReturnType()->isUndeducedType()) {
13356 // If the function has a deduced result type but contains no 'return'
13357 // statements, the result type as written must be exactly 'auto', and
13358 // the deduced result type is 'void'.
13359 if (!FD->getReturnType()->getAs<AutoType>()) {
13360 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13361 << FD->getReturnType();
13362 FD->setInvalidDecl();
13363 } else {
13364 // Substitute 'void' for the 'auto' in the type.
13365 TypeLoc ResultType = getReturnTypeLoc(FD);
13366 Context.adjustDeducedFunctionResultType(
13367 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13368 }
13369 }
13370 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13371 // In C++11, we don't use 'auto' deduction rules for lambda call
13372 // operators because we don't support return type deduction.
13373 auto *LSI = getCurLambda();
13374 if (LSI->HasImplicitReturnType) {
13375 deduceClosureReturnType(*LSI);
13376
13377 // C++11 [expr.prim.lambda]p4:
13378 // [...] if there are no return statements in the compound-statement
13379 // [the deduced type is] the type void
13380 QualType RetType =
13381 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13382
13383 // Update the return type to the deduced type.
13384 const FunctionProtoType *Proto =
13385 FD->getType()->getAs<FunctionProtoType>();
13386 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13387 Proto->getExtProtoInfo()));
13388 }
13389 }
13390
13391 // If the function implicitly returns zero (like 'main') or is naked,
13392 // don't complain about missing return statements.
13393 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13394 WP.disableCheckFallThrough();
13395
13396 // MSVC permits the use of pure specifier (=0) on function definition,
13397 // defined at class scope, warn about this non-standard construct.
13398 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13399 Diag(FD->getLocation(), diag::ext_pure_function_definition);
13400
13401 if (!FD->isInvalidDecl()) {
13402 // Don't diagnose unused parameters of defaulted or deleted functions.
13403 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13404 DiagnoseUnusedParameters(FD->parameters());
13405 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13406 FD->getReturnType(), FD);
13407
13408 // If this is a structor, we need a vtable.
13409 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13410 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13411 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13412 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13413
13414 // Try to apply the named return value optimization. We have to check
13415 // if we can do this here because lambdas keep return statements around
13416 // to deduce an implicit return type.
13417 if (FD->getReturnType()->isRecordType() &&
13418 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13419 computeNRVO(Body, getCurFunction());
13420 }
13421
13422 // GNU warning -Wmissing-prototypes:
13423 // Warn if a global function is defined without a previous
13424 // prototype declaration. This warning is issued even if the
13425 // definition itself provides a prototype. The aim is to detect
13426 // global functions that fail to be declared in header files.
13427 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13428 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13429 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13430
13431 if (PossibleZeroParamPrototype) {
13432 // We found a declaration that is not a prototype,
13433 // but that could be a zero-parameter prototype
13434 if (TypeSourceInfo *TI =
13435 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13436 TypeLoc TL = TI->getTypeLoc();
13437 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13438 Diag(PossibleZeroParamPrototype->getLocation(),
13439 diag::note_declaration_not_a_prototype)
13440 << PossibleZeroParamPrototype
13441 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13442 }
13443 }
13444
13445 // GNU warning -Wstrict-prototypes
13446 // Warn if K&R function is defined without a previous declaration.
13447 // This warning is issued only if the definition itself does not provide
13448 // a prototype. Only K&R definitions do not provide a prototype.
13449 // An empty list in a function declarator that is part of a definition
13450 // of that function specifies that the function has no parameters
13451 // (C99 6.7.5.3p14)
13452 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13453 !LangOpts.CPlusPlus) {
13454 TypeSourceInfo *TI = FD->getTypeSourceInfo();
13455 TypeLoc TL = TI->getTypeLoc();
13456 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13457 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13458 }
13459 }
13460
13461 // Warn on CPUDispatch with an actual body.
13462 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13463 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13464 if (!CmpndBody->body_empty())
13465 Diag(CmpndBody->body_front()->getBeginLoc(),
13466 diag::warn_dispatch_body_ignored);
13467
13468 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13469 const CXXMethodDecl *KeyFunction;
13470 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13471 MD->isVirtual() &&
13472 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13473 MD == KeyFunction->getCanonicalDecl()) {
13474 // Update the key-function state if necessary for this ABI.
13475 if (FD->isInlined() &&
13476 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13477 Context.setNonKeyFunction(MD);
13478
13479 // If the newly-chosen key function is already defined, then we
13480 // need to mark the vtable as used retroactively.
13481 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13482 const FunctionDecl *Definition;
13483 if (KeyFunction && KeyFunction->isDefined(Definition))
13484 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13485 } else {
13486 // We just defined they key function; mark the vtable as used.
13487 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13488 }
13489 }
13490 }
13491
13492 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13493 "Function parsing confused");
13494 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13495 assert(MD == getCurMethodDecl() && "Method parsing confused");
13496 MD->setBody(Body);
13497 if (!MD->isInvalidDecl()) {
13498 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13499 MD->getReturnType(), MD);
13500
13501 if (Body)
13502 computeNRVO(Body, getCurFunction());
13503 }
13504 if (getCurFunction()->ObjCShouldCallSuper) {
13505 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13506 << MD->getSelector().getAsString();
13507 getCurFunction()->ObjCShouldCallSuper = false;
13508 }
13509 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13510 const ObjCMethodDecl *InitMethod = nullptr;
13511 bool isDesignated =
13512 MD->isDesignatedInitializerForTheInterface(&InitMethod);
13513 assert(isDesignated && InitMethod);
13514 (void)isDesignated;
13515
13516 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13517 auto IFace = MD->getClassInterface();
13518 if (!IFace)
13519 return false;
13520 auto SuperD = IFace->getSuperClass();
13521 if (!SuperD)
13522 return false;
13523 return SuperD->getIdentifier() ==
13524 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13525 };
13526 // Don't issue this warning for unavailable inits or direct subclasses
13527 // of NSObject.
13528 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13529 Diag(MD->getLocation(),
13530 diag::warn_objc_designated_init_missing_super_call);
13531 Diag(InitMethod->getLocation(),
13532 diag::note_objc_designated_init_marked_here);
13533 }
13534 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13535 }
13536 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13537 // Don't issue this warning for unavaialable inits.
13538 if (!MD->isUnavailable())
13539 Diag(MD->getLocation(),
13540 diag::warn_objc_secondary_init_missing_init_call);
13541 getCurFunction()->ObjCWarnForNoInitDelegation = false;
13542 }
13543
13544 diagnoseImplicitlyRetainedSelf(*this);
13545 } else {
13546 // Parsing the function declaration failed in some way. Pop the fake scope
13547 // we pushed on.
13548 PopFunctionScopeInfo(ActivePolicy, dcl);
13549 return nullptr;
13550 }
13551
13552 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13553 DiagnoseUnguardedAvailabilityViolations(dcl);
13554
13555 assert(!getCurFunction()->ObjCShouldCallSuper &&
13556 "This should only be set for ObjC methods, which should have been "
13557 "handled in the block above.");
13558
13559 // Verify and clean out per-function state.
13560 if (Body && (!FD || !FD->isDefaulted())) {
13561 // C++ constructors that have function-try-blocks can't have return
13562 // statements in the handlers of that block. (C++ [except.handle]p14)
13563 // Verify this.
13564 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13565 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13566
13567 // Verify that gotos and switch cases don't jump into scopes illegally.
13568 if (getCurFunction()->NeedsScopeChecking() &&
13569 !PP.isCodeCompletionEnabled())
13570 DiagnoseInvalidJumps(Body);
13571
13572 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13573 if (!Destructor->getParent()->isDependentType())
13574 CheckDestructor(Destructor);
13575
13576 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13577 Destructor->getParent());
13578 }
13579
13580 // If any errors have occurred, clear out any temporaries that may have
13581 // been leftover. This ensures that these temporaries won't be picked up for
13582 // deletion in some later function.
13583 if (getDiagnostics().hasErrorOccurred() ||
13584 getDiagnostics().getSuppressAllDiagnostics()) {
13585 DiscardCleanupsInEvaluationContext();
13586 }
13587 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13588 !isa<FunctionTemplateDecl>(dcl)) {
13589 // Since the body is valid, issue any analysis-based warnings that are
13590 // enabled.
13591 ActivePolicy = &WP;
13592 }
13593
13594 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13595 (!CheckConstexprFunctionDecl(FD) ||
13596 !CheckConstexprFunctionBody(FD, Body)))
13597 FD->setInvalidDecl();
13598
13599 if (FD && FD->hasAttr<NakedAttr>()) {
13600 for (const Stmt *S : Body->children()) {
13601 // Allow local register variables without initializer as they don't
13602 // require prologue.
13603 bool RegisterVariables = false;
13604 if (auto *DS = dyn_cast<DeclStmt>(S)) {
13605 for (const auto *Decl : DS->decls()) {
13606 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13607 RegisterVariables =
13608 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13609 if (!RegisterVariables)
13610 break;
13611 }
13612 }
13613 }
13614 if (RegisterVariables)
13615 continue;
13616 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13617 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13618 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13619 FD->setInvalidDecl();
13620 break;
13621 }
13622 }
13623 }
13624
13625 assert(ExprCleanupObjects.size() ==
13626 ExprEvalContexts.back().NumCleanupObjects &&
13627 "Leftover temporaries in function");
13628 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13629 assert(MaybeODRUseExprs.empty() &&
13630 "Leftover expressions for odr-use checking");
13631 }
13632
13633 if (!IsInstantiation)
13634 PopDeclContext();
13635
13636 PopFunctionScopeInfo(ActivePolicy, dcl);
13637 // If any errors have occurred, clear out any temporaries that may have
13638 // been leftover. This ensures that these temporaries won't be picked up for
13639 // deletion in some later function.
13640 if (getDiagnostics().hasErrorOccurred()) {
13641 DiscardCleanupsInEvaluationContext();
13642 }
13643
13644 return dcl;
13645}
13646
13647/// When we finish delayed parsing of an attribute, we must attach it to the
13648/// relevant Decl.
13649void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13650 ParsedAttributes &Attrs) {
13651 // Always attach attributes to the underlying decl.
13652 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13653 D = TD->getTemplatedDecl();
13654 ProcessDeclAttributeList(S, D, Attrs);
13655
13656 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13657 if (Method->isStatic())
13658 checkThisInStaticMemberFunctionAttributes(Method);
13659}
13660
13661/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13662/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13663NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13664 IdentifierInfo &II, Scope *S) {
13665 // Find the scope in which the identifier is injected and the corresponding
13666 // DeclContext.
13667 // FIXME: C89 does not say what happens if there is no enclosing block scope.
13668 // In that case, we inject the declaration into the translation unit scope
13669 // instead.
13670 Scope *BlockScope = S;
13671 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13672 BlockScope = BlockScope->getParent();
13673
13674 Scope *ContextScope = BlockScope;
13675 while (!ContextScope->getEntity())
13676 ContextScope = ContextScope->getParent();
13677 ContextRAII SavedContext(*this, ContextScope->getEntity());
13678
13679 // Before we produce a declaration for an implicitly defined
13680 // function, see whether there was a locally-scoped declaration of
13681 // this name as a function or variable. If so, use that
13682 // (non-visible) declaration, and complain about it.
13683 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13684 if (ExternCPrev) {
13685 // We still need to inject the function into the enclosing block scope so
13686 // that later (non-call) uses can see it.
13687 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13688
13689 // C89 footnote 38:
13690 // If in fact it is not defined as having type "function returning int",
13691 // the behavior is undefined.
13692 if (!isa<FunctionDecl>(ExternCPrev) ||
13693 !Context.typesAreCompatible(
13694 cast<FunctionDecl>(ExternCPrev)->getType(),
13695 Context.getFunctionNoProtoType(Context.IntTy))) {
13696 Diag(Loc, diag::ext_use_out_of_scope_declaration)
13697 << ExternCPrev << !getLangOpts().C99;
13698 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13699 return ExternCPrev;
13700 }
13701 }
13702
13703 // Extension in C99. Legal in C90, but warn about it.
13704 unsigned diag_id;
13705 if (II.getName().startswith("__builtin_"))
13706 diag_id = diag::warn_builtin_unknown;
13707 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13708 else if (getLangOpts().OpenCL)
13709 diag_id = diag::err_opencl_implicit_function_decl;
13710 else if (getLangOpts().C99)
13711 diag_id = diag::ext_implicit_function_decl;
13712 else
13713 diag_id = diag::warn_implicit_function_decl;
13714 Diag(Loc, diag_id) << &II;
13715
13716 // If we found a prior declaration of this function, don't bother building
13717 // another one. We've already pushed that one into scope, so there's nothing
13718 // more to do.
13719 if (ExternCPrev)
13720 return ExternCPrev;
13721
13722 // Because typo correction is expensive, only do it if the implicit
13723 // function declaration is going to be treated as an error.
13724 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13725 TypoCorrection Corrected;
13726 DeclFilterCCC<FunctionDecl> CCC{};
13727 if (S && (Corrected =
13728 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13729 S, nullptr, CCC, CTK_NonError)))
13730 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13731 /*ErrorRecovery*/false);
13732 }
13733
13734 // Set a Declarator for the implicit definition: int foo();
13735 const char *Dummy;
13736 AttributeFactory attrFactory;
13737 DeclSpec DS(attrFactory);
13738 unsigned DiagID;
13739 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13740 Context.getPrintingPolicy());
13741 (void)Error; // Silence warning.
13742 assert(!Error && "Error setting up implicit decl!");
13743 SourceLocation NoLoc;
13744 Declarator D(DS, DeclaratorContext::BlockContext);
13745 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13746 /*IsAmbiguous=*/false,
13747 /*LParenLoc=*/NoLoc,
13748 /*Params=*/nullptr,
13749 /*NumParams=*/0,
13750 /*EllipsisLoc=*/NoLoc,
13751 /*RParenLoc=*/NoLoc,
13752 /*RefQualifierIsLvalueRef=*/true,
13753 /*RefQualifierLoc=*/NoLoc,
13754 /*MutableLoc=*/NoLoc, EST_None,
13755 /*ESpecRange=*/SourceRange(),
13756 /*Exceptions=*/nullptr,
13757 /*ExceptionRanges=*/nullptr,
13758 /*NumExceptions=*/0,
13759 /*NoexceptExpr=*/nullptr,
13760 /*ExceptionSpecTokens=*/nullptr,
13761 /*DeclsInPrototype=*/None, Loc,
13762 Loc, D),
13763 std::move(DS.getAttributes()), SourceLocation());
13764 D.SetIdentifier(&II, Loc);
13765
13766 // Insert this function into the enclosing block scope.
13767 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13768 FD->setImplicit();
13769
13770 AddKnownFunctionAttributes(FD);
13771
13772 return FD;
13773}
13774
13775/// Adds any function attributes that we know a priori based on
13776/// the declaration of this function.
13777///
13778/// These attributes can apply both to implicitly-declared builtins
13779/// (like __builtin___printf_chk) or to library-declared functions
13780/// like NSLog or printf.
13781///
13782/// We need to check for duplicate attributes both here and where user-written
13783/// attributes are applied to declarations.
13784void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13785 if (FD->isInvalidDecl())
13786 return;
13787
13788 // If this is a built-in function, map its builtin attributes to
13789 // actual attributes.
13790 if (unsigned BuiltinID = FD->getBuiltinID()) {
13791 // Handle printf-formatting attributes.
13792 unsigned FormatIdx;
13793 bool HasVAListArg;
13794 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13795 if (!FD->hasAttr<FormatAttr>()) {
13796 const char *fmt = "printf";
13797 unsigned int NumParams = FD->getNumParams();
13798 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13799 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13800 fmt = "NSString";
13801 FD->addAttr(FormatAttr::CreateImplicit(Context,
13802 &Context.Idents.get(fmt),
13803 FormatIdx+1,
13804 HasVAListArg ? 0 : FormatIdx+2,
13805 FD->getLocation()));
13806 }
13807 }
13808 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13809 HasVAListArg)) {
13810 if (!FD->hasAttr<FormatAttr>())
13811 FD->addAttr(FormatAttr::CreateImplicit(Context,
13812 &Context.Idents.get("scanf"),
13813 FormatIdx+1,
13814 HasVAListArg ? 0 : FormatIdx+2,
13815 FD->getLocation()));
13816 }
13817
13818 // Handle automatically recognized callbacks.
13819 SmallVector<int, 4> Encoding;
13820 if (!FD->hasAttr<CallbackAttr>() &&
13821 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13822 FD->addAttr(CallbackAttr::CreateImplicit(
13823 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13824
13825 // Mark const if we don't care about errno and that is the only thing
13826 // preventing the function from being const. This allows IRgen to use LLVM
13827 // intrinsics for such functions.
13828 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13829 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13830 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13831
13832 // We make "fma" on some platforms const because we know it does not set
13833 // errno in those environments even though it could set errno based on the
13834 // C standard.
13835 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13836 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13837 !FD->hasAttr<ConstAttr>()) {
13838 switch (BuiltinID) {
13839 case Builtin::BI__builtin_fma:
13840 case Builtin::BI__builtin_fmaf:
13841 case Builtin::BI__builtin_fmal:
13842 case Builtin::BIfma:
13843 case Builtin::BIfmaf:
13844 case Builtin::BIfmal:
13845 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13846 break;
13847 default:
13848 break;
13849 }
13850 }
13851
13852 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13853 !FD->hasAttr<ReturnsTwiceAttr>())
13854 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13855 FD->getLocation()));
13856 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13857 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13858 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13859 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13860 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13861 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13862 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13863 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13864 // Add the appropriate attribute, depending on the CUDA compilation mode
13865 // and which target the builtin belongs to. For example, during host
13866 // compilation, aux builtins are __device__, while the rest are __host__.
13867 if (getLangOpts().CUDAIsDevice !=
13868 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13869 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13870 else
13871 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13872 }
13873 }
13874
13875 // If C++ exceptions are enabled but we are told extern "C" functions cannot
13876 // throw, add an implicit nothrow attribute to any extern "C" function we come
13877 // across.
13878 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13879 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13880 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13881 if (!FPT || FPT->getExceptionSpecType() == EST_None)
13882 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13883 }
13884
13885 IdentifierInfo *Name = FD->getIdentifier();
13886 if (!Name)
13887 return;
13888 if ((!getLangOpts().CPlusPlus &&
13889 FD->getDeclContext()->isTranslationUnit()) ||
13890 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13891 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13892 LinkageSpecDecl::lang_c)) {
13893 // Okay: this could be a libc/libm/Objective-C function we know
13894 // about.
13895 } else
13896 return;
13897
13898 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13899 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13900 // target-specific builtins, perhaps?
13901 if (!FD->hasAttr<FormatAttr>())
13902 FD->addAttr(FormatAttr::CreateImplicit(Context,
13903 &Context.Idents.get("printf"), 2,
13904 Name->isStr("vasprintf") ? 0 : 3,
13905 FD->getLocation()));
13906 }
13907
13908 if (Name->isStr("__CFStringMakeConstantString")) {
13909 // We already have a __builtin___CFStringMakeConstantString,
13910 // but builds that use -fno-constant-cfstrings don't go through that.
13911 if (!FD->hasAttr<FormatArgAttr>())
13912 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13913 FD->getLocation()));
13914 }
13915}
13916
13917TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13918 TypeSourceInfo *TInfo) {
13919 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13920 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13921
13922 if (!TInfo) {
13923 assert(D.isInvalidType() && "no declarator info for valid type");
13924 TInfo = Context.getTrivialTypeSourceInfo(T);
13925 }
13926
13927 // Scope manipulation handled by caller.
13928 TypedefDecl *NewTD =
13929 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13930 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13931
13932 // Bail out immediately if we have an invalid declaration.
13933 if (D.isInvalidType()) {
13934 NewTD->setInvalidDecl();
13935 return NewTD;
13936 }
13937
13938 if (D.getDeclSpec().isModulePrivateSpecified()) {
13939 if (CurContext->isFunctionOrMethod())
13940 Diag(NewTD->getLocation(), diag::err_module_private_local)
13941 << 2 << NewTD->getDeclName()
13942 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13943 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13944 else
13945 NewTD->setModulePrivate();
13946 }
13947
13948 // C++ [dcl.typedef]p8:
13949 // If the typedef declaration defines an unnamed class (or
13950 // enum), the first typedef-name declared by the declaration
13951 // to be that class type (or enum type) is used to denote the
13952 // class type (or enum type) for linkage purposes only.
13953 // We need to check whether the type was declared in the declaration.
13954 switch (D.getDeclSpec().getTypeSpecType()) {
13955 case TST_enum:
13956 case TST_struct:
13957 case TST_interface:
13958 case TST_union:
13959 case TST_class: {
13960 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13961 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13962 break;
13963 }
13964
13965 default:
13966 break;
13967 }
13968
13969 return NewTD;
13970}
13971
13972/// Check that this is a valid underlying type for an enum declaration.
13973bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13974 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13975 QualType T = TI->getType();
13976
13977 if (T->isDependentType())
13978 return false;
13979
13980 if (const BuiltinType *BT = T->getAs<BuiltinType>())
13981 if (BT->isInteger())
13982 return false;
13983
13984 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13985 return true;
13986}
13987
13988/// Check whether this is a valid redeclaration of a previous enumeration.
13989/// \return true if the redeclaration was invalid.
13990bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13991 QualType EnumUnderlyingTy, bool IsFixed,
13992 const EnumDecl *Prev) {
13993 if (IsScoped != Prev->isScoped()) {
13994 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13995 << Prev->isScoped();
13996 Diag(Prev->getLocation(), diag::note_previous_declaration);
13997 return true;
13998 }
13999
14000 if (IsFixed && Prev->isFixed()) {
14001 if (!EnumUnderlyingTy->isDependentType() &&
14002 !Prev->getIntegerType()->isDependentType() &&
14003 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14004 Prev->getIntegerType())) {
14005 // TODO: Highlight the underlying type of the redeclaration.
14006 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14007 << EnumUnderlyingTy << Prev->getIntegerType();
14008 Diag(Prev->getLocation(), diag::note_previous_declaration)
14009 << Prev->getIntegerTypeRange();
14010 return true;
14011 }
14012 } else if (IsFixed != Prev->isFixed()) {
14013 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14014 << Prev->isFixed();
14015 Diag(Prev->getLocation(), diag::note_previous_declaration);
14016 return true;
14017 }
14018
14019 return false;
14020}
14021
14022/// Get diagnostic %select index for tag kind for
14023/// redeclaration diagnostic message.
14024/// WARNING: Indexes apply to particular diagnostics only!
14025///
14026/// \returns diagnostic %select index.
14027static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14028 switch (Tag) {
14029 case TTK_Struct: return 0;
14030 case TTK_Interface: return 1;
14031 case TTK_Class: return 2;
14032 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14033 }
14034}
14035
14036/// Determine if tag kind is a class-key compatible with
14037/// class for redeclaration (class, struct, or __interface).
14038///
14039/// \returns true iff the tag kind is compatible.
14040static bool isClassCompatTagKind(TagTypeKind Tag)
14041{
14042 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14043}
14044
14045Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14046 TagTypeKind TTK) {
14047 if (isa<TypedefDecl>(PrevDecl))
14048 return NTK_Typedef;
14049 else if (isa<TypeAliasDecl>(PrevDecl))
14050 return NTK_TypeAlias;
14051 else if (isa<ClassTemplateDecl>(PrevDecl))
14052 return NTK_Template;
14053 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14054 return NTK_TypeAliasTemplate;
14055 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14056 return NTK_TemplateTemplateArgument;
14057 switch (TTK) {
14058 case TTK_Struct:
14059 case TTK_Interface:
14060 case TTK_Class:
14061 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14062 case TTK_Union:
14063 return NTK_NonUnion;
14064 case TTK_Enum:
14065 return NTK_NonEnum;
14066 }
14067 llvm_unreachable("invalid TTK");
14068}
14069
14070/// Determine whether a tag with a given kind is acceptable
14071/// as a redeclaration of the given tag declaration.
14072///
14073/// \returns true if the new tag kind is acceptable, false otherwise.
14074bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14075 TagTypeKind NewTag, bool isDefinition,
14076 SourceLocation NewTagLoc,
14077 const IdentifierInfo *Name) {
14078 // C++ [dcl.type.elab]p3:
14079 // The class-key or enum keyword present in the
14080 // elaborated-type-specifier shall agree in kind with the
14081 // declaration to which the name in the elaborated-type-specifier
14082 // refers. This rule also applies to the form of
14083 // elaborated-type-specifier that declares a class-name or
14084 // friend class since it can be construed as referring to the
14085 // definition of the class. Thus, in any
14086 // elaborated-type-specifier, the enum keyword shall be used to
14087 // refer to an enumeration (7.2), the union class-key shall be
14088 // used to refer to a union (clause 9), and either the class or
14089 // struct class-key shall be used to refer to a class (clause 9)
14090 // declared using the class or struct class-key.
14091 TagTypeKind OldTag = Previous->getTagKind();
14092 if (OldTag != NewTag &&
14093 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14094 return false;
14095
14096 // Tags are compatible, but we might still want to warn on mismatched tags.
14097 // Non-class tags can't be mismatched at this point.
14098 if (!isClassCompatTagKind(NewTag))
14099 return true;
14100
14101 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14102 // by our warning analysis. We don't want to warn about mismatches with (eg)
14103 // declarations in system headers that are designed to be specialized, but if
14104 // a user asks us to warn, we should warn if their code contains mismatched
14105 // declarations.
14106 auto IsIgnoredLoc = [&](SourceLocation Loc) {
14107 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14108 Loc);
14109 };
14110 if (IsIgnoredLoc(NewTagLoc))
14111 return true;
14112
14113 auto IsIgnored = [&](const TagDecl *Tag) {
14114 return IsIgnoredLoc(Tag->getLocation());
14115 };
14116 while (IsIgnored(Previous)) {
14117 Previous = Previous->getPreviousDecl();
14118 if (!Previous)
14119 return true;
14120 OldTag = Previous->getTagKind();
14121 }
14122
14123 bool isTemplate = false;
14124 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14125 isTemplate = Record->getDescribedClassTemplate();
14126
14127 if (inTemplateInstantiation()) {
14128 if (OldTag != NewTag) {
14129 // In a template instantiation, do not offer fix-its for tag mismatches
14130 // since they usually mess up the template instead of fixing the problem.
14131 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14132 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14133 << getRedeclDiagFromTagKind(OldTag);
14134 // FIXME: Note previous location?
14135 }
14136 return true;
14137 }
14138
14139 if (isDefinition) {
14140 // On definitions, check all previous tags and issue a fix-it for each
14141 // one that doesn't match the current tag.
14142 if (Previous->getDefinition()) {
14143 // Don't suggest fix-its for redefinitions.
14144 return true;
14145 }
14146
14147 bool previousMismatch = false;
14148 for (const TagDecl *I : Previous->redecls()) {
14149 if (I->getTagKind() != NewTag) {
14150 // Ignore previous declarations for which the warning was disabled.
14151 if (IsIgnored(I))
14152 continue;
14153
14154 if (!previousMismatch) {
14155 previousMismatch = true;
14156 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14157 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14158 << getRedeclDiagFromTagKind(I->getTagKind());
14159 }
14160 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14161 << getRedeclDiagFromTagKind(NewTag)
14162 << FixItHint::CreateReplacement(I->getInnerLocStart(),
14163 TypeWithKeyword::getTagTypeKindName(NewTag));
14164 }
14165 }
14166 return true;
14167 }
14168
14169 // Identify the prevailing tag kind: this is the kind of the definition (if
14170 // there is a non-ignored definition), or otherwise the kind of the prior
14171 // (non-ignored) declaration.
14172 const TagDecl *PrevDef = Previous->getDefinition();
14173 if (PrevDef && IsIgnored(PrevDef))
14174 PrevDef = nullptr;
14175 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14176 if (Redecl->getTagKind() != NewTag) {
14177 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14178 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14179 << getRedeclDiagFromTagKind(OldTag);
14180 Diag(Redecl->getLocation(), diag::note_previous_use);
14181
14182 // If there is a previous definition, suggest a fix-it.
14183 if (PrevDef) {
14184 Diag(NewTagLoc, diag::note_struct_class_suggestion)
14185 << getRedeclDiagFromTagKind(Redecl->getTagKind())
14186 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14187 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14188 }
14189 }
14190
14191 return true;
14192}
14193
14194/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14195/// from an outer enclosing namespace or file scope inside a friend declaration.
14196/// This should provide the commented out code in the following snippet:
14197/// namespace N {
14198/// struct X;
14199/// namespace M {
14200/// struct Y { friend struct /*N::*/ X; };
14201/// }
14202/// }
14203static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14204 SourceLocation NameLoc) {
14205 // While the decl is in a namespace, do repeated lookup of that name and see
14206 // if we get the same namespace back. If we do not, continue until
14207 // translation unit scope, at which point we have a fully qualified NNS.
14208 SmallVector<IdentifierInfo *, 4> Namespaces;
14209 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14210 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14211 // This tag should be declared in a namespace, which can only be enclosed by
14212 // other namespaces. Bail if there's an anonymous namespace in the chain.
14213 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14214 if (!Namespace || Namespace->isAnonymousNamespace())
14215 return FixItHint();
14216 IdentifierInfo *II = Namespace->getIdentifier();
14217 Namespaces.push_back(II);
14218 NamedDecl *Lookup = SemaRef.LookupSingleName(
14219 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14220 if (Lookup == Namespace)
14221 break;
14222 }
14223
14224 // Once we have all the namespaces, reverse them to go outermost first, and
14225 // build an NNS.
14226 SmallString<64> Insertion;
14227 llvm::raw_svector_ostream OS(Insertion);
14228 if (DC->isTranslationUnit())
14229 OS << "::";
14230 std::reverse(Namespaces.begin(), Namespaces.end());
14231 for (auto *II : Namespaces)
14232 OS << II->getName() << "::";
14233 return FixItHint::CreateInsertion(NameLoc, Insertion);
14234}
14235
14236/// Determine whether a tag originally declared in context \p OldDC can
14237/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14238/// found a declaration in \p OldDC as a previous decl, perhaps through a
14239/// using-declaration).
14240static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14241 DeclContext *NewDC) {
14242 OldDC = OldDC->getRedeclContext();
14243 NewDC = NewDC->getRedeclContext();
14244
14245 if (OldDC->Equals(NewDC))
14246 return true;
14247
14248 // In MSVC mode, we allow a redeclaration if the contexts are related (either
14249 // encloses the other).
14250 if (S.getLangOpts().MSVCCompat &&
14251 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14252 return true;
14253
14254 return false;
14255}
14256
14257/// This is invoked when we see 'struct foo' or 'struct {'. In the
14258/// former case, Name will be non-null. In the later case, Name will be null.
14259/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14260/// reference/declaration/definition of a tag.
14261///
14262/// \param IsTypeSpecifier \c true if this is a type-specifier (or
14263/// trailing-type-specifier) other than one in an alias-declaration.
14264///
14265/// \param SkipBody If non-null, will be set to indicate if the caller should
14266/// skip the definition of this tag and treat it as if it were a declaration.
14267Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14268 SourceLocation KWLoc, CXXScopeSpec &SS,
14269 IdentifierInfo *Name, SourceLocation NameLoc,
14270 const ParsedAttributesView &Attrs, AccessSpecifier AS,
14271 SourceLocation ModulePrivateLoc,
14272 MultiTemplateParamsArg TemplateParameterLists,
14273 bool &OwnedDecl, bool &IsDependent,
14274 SourceLocation ScopedEnumKWLoc,
14275 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14276 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14277 SkipBodyInfo *SkipBody) {
14278 // If this is not a definition, it must have a name.
14279 IdentifierInfo *OrigName = Name;
14280 assert((Name != nullptr || TUK == TUK_Definition) &&
14281 "Nameless record must be a definition!");
14282 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14283
14284 OwnedDecl = false;
14285 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14286 bool ScopedEnum = ScopedEnumKWLoc.isValid();
14287
14288 // FIXME: Check member specializations more carefully.
14289 bool isMemberSpecialization = false;
14290 bool Invalid = false;
14291
14292 // We only need to do this matching if we have template parameters
14293 // or a scope specifier, which also conveniently avoids this work
14294 // for non-C++ cases.
14295 if (TemplateParameterLists.size() > 0 ||
14296 (SS.isNotEmpty() && TUK != TUK_Reference)) {
14297 if (TemplateParameterList *TemplateParams =
14298 MatchTemplateParametersToScopeSpecifier(
14299 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14300 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14301 if (Kind == TTK_Enum) {
14302 Diag(KWLoc, diag::err_enum_template);
14303 return nullptr;
14304 }
14305
14306 if (TemplateParams->size() > 0) {
14307 // This is a declaration or definition of a class template (which may
14308 // be a member of another template).
14309
14310 if (Invalid)
14311 return nullptr;
14312
14313 OwnedDecl = false;
14314 DeclResult Result = CheckClassTemplate(
14315 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14316 AS, ModulePrivateLoc,
14317 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14318 TemplateParameterLists.data(), SkipBody);
14319 return Result.get();
14320 } else {
14321 // The "template<>" header is extraneous.
14322 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14323 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14324 isMemberSpecialization = true;
14325 }
14326 }
14327 }
14328
14329 // Figure out the underlying type if this a enum declaration. We need to do
14330 // this early, because it's needed to detect if this is an incompatible
14331 // redeclaration.
14332 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14333 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14334
14335 if (Kind == TTK_Enum) {
14336 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14337 // No underlying type explicitly specified, or we failed to parse the
14338 // type, default to int.
14339 EnumUnderlying = Context.IntTy.getTypePtr();
14340 } else if (UnderlyingType.get()) {
14341 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14342 // integral type; any cv-qualification is ignored.
14343 TypeSourceInfo *TI = nullptr;
14344 GetTypeFromParser(UnderlyingType.get(), &TI);
14345 EnumUnderlying = TI;
14346
14347 if (CheckEnumUnderlyingType(TI))
14348 // Recover by falling back to int.
14349 EnumUnderlying = Context.IntTy.getTypePtr();
14350
14351 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14352 UPPC_FixedUnderlyingType))
14353 EnumUnderlying = Context.IntTy.getTypePtr();
14354
14355 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14356 // For MSVC ABI compatibility, unfixed enums must use an underlying type
14357 // of 'int'. However, if this is an unfixed forward declaration, don't set
14358 // the underlying type unless the user enables -fms-compatibility. This
14359 // makes unfixed forward declared enums incomplete and is more conforming.
14360 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14361 EnumUnderlying = Context.IntTy.getTypePtr();
14362 }
14363 }
14364
14365 DeclContext *SearchDC = CurContext;
14366 DeclContext *DC = CurContext;
14367 bool isStdBadAlloc = false;
14368 bool isStdAlignValT = false;
14369
14370 RedeclarationKind Redecl = forRedeclarationInCurContext();
14371 if (TUK == TUK_Friend || TUK == TUK_Reference)
14372 Redecl = NotForRedeclaration;
14373
14374 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14375 /// implemented asks for structural equivalence checking, the returned decl
14376 /// here is passed back to the parser, allowing the tag body to be parsed.
14377 auto createTagFromNewDecl = [&]() -> TagDecl * {
14378 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14379 // If there is an identifier, use the location of the identifier as the
14380 // location of the decl, otherwise use the location of the struct/union
14381 // keyword.
14382 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14383 TagDecl *New = nullptr;
14384
14385 if (Kind == TTK_Enum) {
14386 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14387 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14388 // If this is an undefined enum, bail.
14389 if (TUK != TUK_Definition && !Invalid)
14390 return nullptr;
14391 if (EnumUnderlying) {
14392 EnumDecl *ED = cast<EnumDecl>(New);
14393 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14394 ED->setIntegerTypeSourceInfo(TI);
14395 else
14396 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14397 ED->setPromotionType(ED->getIntegerType());
14398 }
14399 } else { // struct/union
14400 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14401 nullptr);
14402 }
14403
14404 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14405 // Add alignment attributes if necessary; these attributes are checked
14406 // when the ASTContext lays out the structure.
14407 //
14408 // It is important for implementing the correct semantics that this
14409 // happen here (in ActOnTag). The #pragma pack stack is
14410 // maintained as a result of parser callbacks which can occur at
14411 // many points during the parsing of a struct declaration (because
14412 // the #pragma tokens are effectively skipped over during the
14413 // parsing of the struct).
14414 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14415 AddAlignmentAttributesForRecord(RD);
14416 AddMsStructLayoutForRecord(RD);
14417 }
14418 }
14419 New->setLexicalDeclContext(CurContext);
14420 return New;
14421 };
14422
14423 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14424 if (Name && SS.isNotEmpty()) {
14425 // We have a nested-name tag ('struct foo::bar').
14426
14427 // Check for invalid 'foo::'.
14428 if (SS.isInvalid()) {
14429 Name = nullptr;
14430 goto CreateNewDecl;
14431 }
14432
14433 // If this is a friend or a reference to a class in a dependent
14434 // context, don't try to make a decl for it.
14435 if (TUK == TUK_Friend || TUK == TUK_Reference) {
14436 DC = computeDeclContext(SS, false);
14437 if (!DC) {
14438 IsDependent = true;
14439 return nullptr;
14440 }
14441 } else {
14442 DC = computeDeclContext(SS, true);
14443 if (!DC) {
14444 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14445 << SS.getRange();
14446 return nullptr;
14447 }
14448 }
14449
14450 if (RequireCompleteDeclContext(SS, DC))
14451 return nullptr;
14452
14453 SearchDC = DC;
14454 // Look-up name inside 'foo::'.
14455 LookupQualifiedName(Previous, DC);
14456
14457 if (Previous.isAmbiguous())
14458 return nullptr;
14459
14460 if (Previous.empty()) {
14461 // Name lookup did not find anything. However, if the
14462 // nested-name-specifier refers to the current instantiation,
14463 // and that current instantiation has any dependent base
14464 // classes, we might find something at instantiation time: treat
14465 // this as a dependent elaborated-type-specifier.
14466 // But this only makes any sense for reference-like lookups.
14467 if (Previous.wasNotFoundInCurrentInstantiation() &&
14468 (TUK == TUK_Reference || TUK == TUK_Friend)) {
14469 IsDependent = true;
14470 return nullptr;
14471 }
14472
14473 // A tag 'foo::bar' must already exist.
14474 Diag(NameLoc, diag::err_not_tag_in_scope)
14475 << Kind << Name << DC << SS.getRange();
14476 Name = nullptr;
14477 Invalid = true;
14478 goto CreateNewDecl;
14479 }
14480 } else if (Name) {
14481 // C++14 [class.mem]p14:
14482 // If T is the name of a class, then each of the following shall have a
14483 // name different from T:
14484 // -- every member of class T that is itself a type
14485 if (TUK != TUK_Reference && TUK != TUK_Friend &&
14486 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14487 return nullptr;
14488
14489 // If this is a named struct, check to see if there was a previous forward
14490 // declaration or definition.
14491 // FIXME: We're looking into outer scopes here, even when we
14492 // shouldn't be. Doing so can result in ambiguities that we
14493 // shouldn't be diagnosing.
14494 LookupName(Previous, S);
14495
14496 // When declaring or defining a tag, ignore ambiguities introduced
14497 // by types using'ed into this scope.
14498 if (Previous.isAmbiguous() &&
14499 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14500 LookupResult::Filter F = Previous.makeFilter();
14501 while (F.hasNext()) {
14502 NamedDecl *ND = F.next();
14503 if (!ND->getDeclContext()->getRedeclContext()->Equals(
14504 SearchDC->getRedeclContext()))
14505 F.erase();
14506 }
14507 F.done();
14508 }
14509
14510 // C++11 [namespace.memdef]p3:
14511 // If the name in a friend declaration is neither qualified nor
14512 // a template-id and the declaration is a function or an
14513 // elaborated-type-specifier, the lookup to determine whether
14514 // the entity has been previously declared shall not consider
14515 // any scopes outside the innermost enclosing namespace.
14516 //
14517 // MSVC doesn't implement the above rule for types, so a friend tag
14518 // declaration may be a redeclaration of a type declared in an enclosing
14519 // scope. They do implement this rule for friend functions.
14520 //
14521 // Does it matter that this should be by scope instead of by
14522 // semantic context?
14523 if (!Previous.empty() && TUK == TUK_Friend) {
14524 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14525 LookupResult::Filter F = Previous.makeFilter();
14526 bool FriendSawTagOutsideEnclosingNamespace = false;
14527 while (F.hasNext()) {
14528 NamedDecl *ND = F.next();
14529 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14530 if (DC->isFileContext() &&
14531 !EnclosingNS->Encloses(ND->getDeclContext())) {
14532 if (getLangOpts().MSVCCompat)
14533 FriendSawTagOutsideEnclosingNamespace = true;
14534 else
14535 F.erase();
14536 }
14537 }
14538 F.done();
14539
14540 // Diagnose this MSVC extension in the easy case where lookup would have
14541 // unambiguously found something outside the enclosing namespace.
14542 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14543 NamedDecl *ND = Previous.getFoundDecl();
14544 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14545 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14546 }
14547 }
14548
14549 // Note: there used to be some attempt at recovery here.
14550 if (Previous.isAmbiguous())
14551 return nullptr;
14552
14553 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14554 // FIXME: This makes sure that we ignore the contexts associated
14555 // with C structs, unions, and enums when looking for a matching
14556 // tag declaration or definition. See the similar lookup tweak
14557 // in Sema::LookupName; is there a better way to deal with this?
14558 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14559 SearchDC = SearchDC->getParent();
14560 }
14561 }
14562
14563 if (Previous.isSingleResult() &&
14564 Previous.getFoundDecl()->isTemplateParameter()) {
14565 // Maybe we will complain about the shadowed template parameter.
14566 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14567 // Just pretend that we didn't see the previous declaration.
14568 Previous.clear();
14569 }
14570
14571 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14572 DC->Equals(getStdNamespace())) {
14573 if (Name->isStr("bad_alloc")) {
14574 // This is a declaration of or a reference to "std::bad_alloc".
14575 isStdBadAlloc = true;
14576
14577 // If std::bad_alloc has been implicitly declared (but made invisible to
14578 // name lookup), fill in this implicit declaration as the previous
14579 // declaration, so that the declarations get chained appropriately.
14580 if (Previous.empty() && StdBadAlloc)
14581 Previous.addDecl(getStdBadAlloc());
14582 } else if (Name->isStr("align_val_t")) {
14583 isStdAlignValT = true;
14584 if (Previous.empty() && StdAlignValT)
14585 Previous.addDecl(getStdAlignValT());
14586 }
14587 }
14588
14589 // If we didn't find a previous declaration, and this is a reference
14590 // (or friend reference), move to the correct scope. In C++, we
14591 // also need to do a redeclaration lookup there, just in case
14592 // there's a shadow friend decl.
14593 if (Name && Previous.empty() &&
14594 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14595 if (Invalid) goto CreateNewDecl;
14596 assert(SS.isEmpty());
14597
14598 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14599 // C++ [basic.scope.pdecl]p5:
14600 // -- for an elaborated-type-specifier of the form
14601 //
14602 // class-key identifier
14603 //
14604 // if the elaborated-type-specifier is used in the
14605 // decl-specifier-seq or parameter-declaration-clause of a
14606 // function defined in namespace scope, the identifier is
14607 // declared as a class-name in the namespace that contains
14608 // the declaration; otherwise, except as a friend
14609 // declaration, the identifier is declared in the smallest
14610 // non-class, non-function-prototype scope that contains the
14611 // declaration.
14612 //
14613 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14614 // C structs and unions.
14615 //
14616 // It is an error in C++ to declare (rather than define) an enum
14617 // type, including via an elaborated type specifier. We'll
14618 // diagnose that later; for now, declare the enum in the same
14619 // scope as we would have picked for any other tag type.
14620 //
14621 // GNU C also supports this behavior as part of its incomplete
14622 // enum types extension, while GNU C++ does not.
14623 //
14624 // Find the context where we'll be declaring the tag.
14625 // FIXME: We would like to maintain the current DeclContext as the
14626 // lexical context,
14627 SearchDC = getTagInjectionContext(SearchDC);
14628
14629 // Find the scope where we'll be declaring the tag.
14630 S = getTagInjectionScope(S, getLangOpts());
14631 } else {
14632 assert(TUK == TUK_Friend);
14633 // C++ [namespace.memdef]p3:
14634 // If a friend declaration in a non-local class first declares a
14635 // class or function, the friend class or function is a member of
14636 // the innermost enclosing namespace.
14637 SearchDC = SearchDC->getEnclosingNamespaceContext();
14638 }
14639
14640 // In C++, we need to do a redeclaration lookup to properly
14641 // diagnose some problems.
14642 // FIXME: redeclaration lookup is also used (with and without C++) to find a
14643 // hidden declaration so that we don't get ambiguity errors when using a
14644 // type declared by an elaborated-type-specifier. In C that is not correct
14645 // and we should instead merge compatible types found by lookup.
14646 if (getLangOpts().CPlusPlus) {
14647 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14648 LookupQualifiedName(Previous, SearchDC);
14649 } else {
14650 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14651 LookupName(Previous, S);
14652 }
14653 }
14654
14655 // If we have a known previous declaration to use, then use it.
14656 if (Previous.empty() && SkipBody && SkipBody->Previous)
14657 Previous.addDecl(SkipBody->Previous);
14658
14659 if (!Previous.empty()) {
14660 NamedDecl *PrevDecl = Previous.getFoundDecl();
14661 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14662
14663 // It's okay to have a tag decl in the same scope as a typedef
14664 // which hides a tag decl in the same scope. Finding this
14665 // insanity with a redeclaration lookup can only actually happen
14666 // in C++.
14667 //
14668 // This is also okay for elaborated-type-specifiers, which is
14669 // technically forbidden by the current standard but which is
14670 // okay according to the likely resolution of an open issue;
14671 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14672 if (getLangOpts().CPlusPlus) {
14673 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14674 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14675 TagDecl *Tag = TT->getDecl();
14676 if (Tag->getDeclName() == Name &&
14677 Tag->getDeclContext()->getRedeclContext()
14678 ->Equals(TD->getDeclContext()->getRedeclContext())) {
14679 PrevDecl = Tag;
14680 Previous.clear();
14681 Previous.addDecl(Tag);
14682 Previous.resolveKind();
14683 }
14684 }
14685 }
14686 }
14687
14688 // If this is a redeclaration of a using shadow declaration, it must
14689 // declare a tag in the same context. In MSVC mode, we allow a
14690 // redefinition if either context is within the other.
14691 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14692 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14693 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14694 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14695 !(OldTag && isAcceptableTagRedeclContext(
14696 *this, OldTag->getDeclContext(), SearchDC))) {
14697 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14698 Diag(Shadow->getTargetDecl()->getLocation(),
14699 diag::note_using_decl_target);
14700 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14701 << 0;
14702 // Recover by ignoring the old declaration.
14703 Previous.clear();
14704 goto CreateNewDecl;
14705 }
14706 }
14707
14708 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14709 // If this is a use of a previous tag, or if the tag is already declared
14710 // in the same scope (so that the definition/declaration completes or
14711 // rementions the tag), reuse the decl.
14712 if (TUK == TUK_Reference || TUK == TUK_Friend ||
14713 isDeclInScope(DirectPrevDecl, SearchDC, S,
14714 SS.isNotEmpty() || isMemberSpecialization)) {
14715 // Make sure that this wasn't declared as an enum and now used as a
14716 // struct or something similar.
14717 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14718 TUK == TUK_Definition, KWLoc,
14719 Name)) {
14720 bool SafeToContinue
14721 = (PrevTagDecl->getTagKind() != TTK_Enum &&
14722 Kind != TTK_Enum);
14723 if (SafeToContinue)
14724 Diag(KWLoc, diag::err_use_with_wrong_tag)
14725 << Name
14726 << FixItHint::CreateReplacement(SourceRange(KWLoc),
14727 PrevTagDecl->getKindName());
14728 else
14729 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14730 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14731
14732 if (SafeToContinue)
14733 Kind = PrevTagDecl->getTagKind();
14734 else {
14735 // Recover by making this an anonymous redefinition.
14736 Name = nullptr;
14737 Previous.clear();
14738 Invalid = true;
14739 }
14740 }
14741
14742 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14743 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14744
14745 // If this is an elaborated-type-specifier for a scoped enumeration,
14746 // the 'class' keyword is not necessary and not permitted.
14747 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14748 if (ScopedEnum)
14749 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14750 << PrevEnum->isScoped()
14751 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14752 return PrevTagDecl;
14753 }
14754
14755 QualType EnumUnderlyingTy;
14756 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14757 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14758 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14759 EnumUnderlyingTy = QualType(T, 0);
14760
14761 // All conflicts with previous declarations are recovered by
14762 // returning the previous declaration, unless this is a definition,
14763 // in which case we want the caller to bail out.
14764 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14765 ScopedEnum, EnumUnderlyingTy,
14766 IsFixed, PrevEnum))
14767 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14768 }
14769
14770 // C++11 [class.mem]p1:
14771 // A member shall not be declared twice in the member-specification,
14772 // except that a nested class or member class template can be declared
14773 // and then later defined.
14774 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14775 S->isDeclScope(PrevDecl)) {
14776 Diag(NameLoc, diag::ext_member_redeclared);
14777 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14778 }
14779
14780 if (!Invalid) {
14781 // If this is a use, just return the declaration we found, unless
14782 // we have attributes.
14783 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14784 if (!Attrs.empty()) {
14785 // FIXME: Diagnose these attributes. For now, we create a new
14786 // declaration to hold them.
14787 } else if (TUK == TUK_Reference &&
14788 (PrevTagDecl->getFriendObjectKind() ==
14789 Decl::FOK_Undeclared ||
14790 PrevDecl->getOwningModule() != getCurrentModule()) &&
14791 SS.isEmpty()) {
14792 // This declaration is a reference to an existing entity, but
14793 // has different visibility from that entity: it either makes
14794 // a friend visible or it makes a type visible in a new module.
14795 // In either case, create a new declaration. We only do this if
14796 // the declaration would have meant the same thing if no prior
14797 // declaration were found, that is, if it was found in the same
14798 // scope where we would have injected a declaration.
14799 if (!getTagInjectionContext(CurContext)->getRedeclContext()
14800 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14801 return PrevTagDecl;
14802 // This is in the injected scope, create a new declaration in
14803 // that scope.
14804 S = getTagInjectionScope(S, getLangOpts());
14805 } else {
14806 return PrevTagDecl;
14807 }
14808 }
14809
14810 // Diagnose attempts to redefine a tag.
14811 if (TUK == TUK_Definition) {
14812 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14813 // If we're defining a specialization and the previous definition
14814 // is from an implicit instantiation, don't emit an error
14815 // here; we'll catch this in the general case below.
14816 bool IsExplicitSpecializationAfterInstantiation = false;
14817 if (isMemberSpecialization) {
14818 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14819 IsExplicitSpecializationAfterInstantiation =
14820 RD->getTemplateSpecializationKind() !=
14821 TSK_ExplicitSpecialization;
14822 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14823 IsExplicitSpecializationAfterInstantiation =
14824 ED->getTemplateSpecializationKind() !=
14825 TSK_ExplicitSpecialization;
14826 }
14827
14828 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14829 // not keep more that one definition around (merge them). However,
14830 // ensure the decl passes the structural compatibility check in
14831 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14832 NamedDecl *Hidden = nullptr;
14833 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14834 // There is a definition of this tag, but it is not visible. We
14835 // explicitly make use of C++'s one definition rule here, and
14836 // assume that this definition is identical to the hidden one
14837 // we already have. Make the existing definition visible and
14838 // use it in place of this one.
14839 if (!getLangOpts().CPlusPlus) {
14840 // Postpone making the old definition visible until after we
14841 // complete parsing the new one and do the structural
14842 // comparison.
14843 SkipBody->CheckSameAsPrevious = true;
14844 SkipBody->New = createTagFromNewDecl();
14845 SkipBody->Previous = Def;
14846 return Def;
14847 } else {
14848 SkipBody->ShouldSkip = true;
14849 SkipBody->Previous = Def;
14850 makeMergedDefinitionVisible(Hidden);
14851 // Carry on and handle it like a normal definition. We'll
14852 // skip starting the definitiion later.
14853 }
14854 } else if (!IsExplicitSpecializationAfterInstantiation) {
14855 // A redeclaration in function prototype scope in C isn't
14856 // visible elsewhere, so merely issue a warning.
14857 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14858 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14859 else
14860 Diag(NameLoc, diag::err_redefinition) << Name;
14861 notePreviousDefinition(Def,
14862 NameLoc.isValid() ? NameLoc : KWLoc);
14863 // If this is a redefinition, recover by making this
14864 // struct be anonymous, which will make any later
14865 // references get the previous definition.
14866 Name = nullptr;
14867 Previous.clear();
14868 Invalid = true;
14869 }
14870 } else {
14871 // If the type is currently being defined, complain
14872 // about a nested redefinition.
14873 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14874 if (TD->isBeingDefined()) {
14875 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14876 Diag(PrevTagDecl->getLocation(),
14877 diag::note_previous_definition);
14878 Name = nullptr;
14879 Previous.clear();
14880 Invalid = true;
14881 }
14882 }
14883
14884 // Okay, this is definition of a previously declared or referenced
14885 // tag. We're going to create a new Decl for it.
14886 }
14887
14888 // Okay, we're going to make a redeclaration. If this is some kind
14889 // of reference, make sure we build the redeclaration in the same DC
14890 // as the original, and ignore the current access specifier.
14891 if (TUK == TUK_Friend || TUK == TUK_Reference) {
14892 SearchDC = PrevTagDecl->getDeclContext();
14893 AS = AS_none;
14894 }
14895 }
14896 // If we get here we have (another) forward declaration or we
14897 // have a definition. Just create a new decl.
14898
14899 } else {
14900 // If we get here, this is a definition of a new tag type in a nested
14901 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14902 // new decl/type. We set PrevDecl to NULL so that the entities
14903 // have distinct types.
14904 Previous.clear();
14905 }
14906 // If we get here, we're going to create a new Decl. If PrevDecl
14907 // is non-NULL, it's a definition of the tag declared by
14908 // PrevDecl. If it's NULL, we have a new definition.
14909
14910 // Otherwise, PrevDecl is not a tag, but was found with tag
14911 // lookup. This is only actually possible in C++, where a few
14912 // things like templates still live in the tag namespace.
14913 } else {
14914 // Use a better diagnostic if an elaborated-type-specifier
14915 // found the wrong kind of type on the first
14916 // (non-redeclaration) lookup.
14917 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14918 !Previous.isForRedeclaration()) {
14919 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14920 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14921 << Kind;
14922 Diag(PrevDecl->getLocation(), diag::note_declared_at);
14923 Invalid = true;
14924
14925 // Otherwise, only diagnose if the declaration is in scope.
14926 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14927 SS.isNotEmpty() || isMemberSpecialization)) {
14928 // do nothing
14929
14930 // Diagnose implicit declarations introduced by elaborated types.
14931 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14932 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14933 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14934 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14935 Invalid = true;
14936
14937 // Otherwise it's a declaration. Call out a particularly common
14938 // case here.
14939 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14940 unsigned Kind = 0;
14941 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14942 Diag(NameLoc, diag::err_tag_definition_of_typedef)
14943 << Name << Kind << TND->getUnderlyingType();
14944 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14945 Invalid = true;
14946
14947 // Otherwise, diagnose.
14948 } else {
14949 // The tag name clashes with something else in the target scope,
14950 // issue an error and recover by making this tag be anonymous.
14951 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14952 notePreviousDefinition(PrevDecl, NameLoc);
14953 Name = nullptr;
14954 Invalid = true;
14955 }
14956
14957 // The existing declaration isn't relevant to us; we're in a
14958 // new scope, so clear out the previous declaration.
14959 Previous.clear();
14960 }
14961 }
14962
14963CreateNewDecl:
14964
14965 TagDecl *PrevDecl = nullptr;
14966 if (Previous.isSingleResult())
14967 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14968
14969 // If there is an identifier, use the location of the identifier as the
14970 // location of the decl, otherwise use the location of the struct/union
14971 // keyword.
14972 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14973
14974 // Otherwise, create a new declaration. If there is a previous
14975 // declaration of the same entity, the two will be linked via
14976 // PrevDecl.
14977 TagDecl *New;
14978
14979 if (Kind == TTK_Enum) {
14980 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14981 // enum X { A, B, C } D; D should chain to X.
14982 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14983 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14984 ScopedEnumUsesClassTag, IsFixed);
14985
14986 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14987 StdAlignValT = cast<EnumDecl>(New);
14988
14989 // If this is an undefined enum, warn.
14990 if (TUK != TUK_Definition && !Invalid) {
14991 TagDecl *Def;
14992 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14993 // C++0x: 7.2p2: opaque-enum-declaration.
14994 // Conflicts are diagnosed above. Do nothing.
14995 }
14996 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14997 Diag(Loc, diag::ext_forward_ref_enum_def)
14998 << New;
14999 Diag(Def->getLocation(), diag::note_previous_definition);
15000 } else {
15001 unsigned DiagID = diag::ext_forward_ref_enum;
15002 if (getLangOpts().MSVCCompat)
15003 DiagID = diag::ext_ms_forward_ref_enum;
15004 else if (getLangOpts().CPlusPlus)
15005 DiagID = diag::err_forward_ref_enum;
15006 Diag(Loc, DiagID);
15007 }
15008 }
15009
15010 if (EnumUnderlying) {
15011 EnumDecl *ED = cast<EnumDecl>(New);
15012 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15013 ED->setIntegerTypeSourceInfo(TI);
15014 else
15015 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15016 ED->setPromotionType(ED->getIntegerType());
15017 assert(ED->isComplete() && "enum with type should be complete");
15018 }
15019 } else {
15020 // struct/union/class
15021
15022 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15023 // struct X { int A; } D; D should chain to X.
15024 if (getLangOpts().CPlusPlus) {
15025 // FIXME: Look for a way to use RecordDecl for simple structs.
15026 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15027 cast_or_null<CXXRecordDecl>(PrevDecl));
15028
15029 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15030 StdBadAlloc = cast<CXXRecordDecl>(New);
15031 } else
15032 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15033 cast_or_null<RecordDecl>(PrevDecl));
15034 }
15035
15036 // C++11 [dcl.type]p3:
15037 // A type-specifier-seq shall not define a class or enumeration [...].
15038 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15039 TUK == TUK_Definition) {
15040 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15041 << Context.getTagDeclType(New);
15042 Invalid = true;
15043 }
15044
15045 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15046 DC->getDeclKind() == Decl::Enum) {
15047 Diag(New->getLocation(), diag::err_type_defined_in_enum)
15048 << Context.getTagDeclType(New);
15049 Invalid = true;
15050 }
15051
15052 // Maybe add qualifier info.
15053 if (SS.isNotEmpty()) {
15054 if (SS.isSet()) {
15055 // If this is either a declaration or a definition, check the
15056 // nested-name-specifier against the current context.
15057 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15058 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15059 isMemberSpecialization))
15060 Invalid = true;
15061
15062 New->setQualifierInfo(SS.getWithLocInContext(Context));
15063 if (TemplateParameterLists.size() > 0) {
15064 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15065 }
15066 }
15067 else
15068 Invalid = true;
15069 }
15070
15071 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15072 // Add alignment attributes if necessary; these attributes are checked when
15073 // the ASTContext lays out the structure.
15074 //
15075 // It is important for implementing the correct semantics that this
15076 // happen here (in ActOnTag). The #pragma pack stack is
15077 // maintained as a result of parser callbacks which can occur at
15078 // many points during the parsing of a struct declaration (because
15079 // the #pragma tokens are effectively skipped over during the
15080 // parsing of the struct).
15081 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15082 AddAlignmentAttributesForRecord(RD);
15083 AddMsStructLayoutForRecord(RD);
15084 }
15085 }
15086
15087 if (ModulePrivateLoc.isValid()) {
15088 if (isMemberSpecialization)
15089 Diag(New->getLocation(), diag::err_module_private_specialization)
15090 << 2
15091 << FixItHint::CreateRemoval(ModulePrivateLoc);
15092 // __module_private__ does not apply to local classes. However, we only
15093 // diagnose this as an error when the declaration specifiers are
15094 // freestanding. Here, we just ignore the __module_private__.
15095 else if (!SearchDC->isFunctionOrMethod())
15096 New->setModulePrivate();
15097 }
15098
15099 // If this is a specialization of a member class (of a class template),
15100 // check the specialization.
15101 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15102 Invalid = true;
15103
15104 // If we're declaring or defining a tag in function prototype scope in C,
15105 // note that this type can only be used within the function and add it to
15106 // the list of decls to inject into the function definition scope.
15107 if ((Name || Kind == TTK_Enum) &&
15108 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15109 if (getLangOpts().CPlusPlus) {
15110 // C++ [dcl.fct]p6:
15111 // Types shall not be defined in return or parameter types.
15112 if (TUK == TUK_Definition && !IsTypeSpecifier) {
15113 Diag(Loc, diag::err_type_defined_in_param_type)
15114 << Name;
15115 Invalid = true;
15116 }
15117 } else if (!PrevDecl) {
15118 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15119 }
15120 }
15121
15122 if (Invalid)
15123 New->setInvalidDecl();
15124
15125 // Set the lexical context. If the tag has a C++ scope specifier, the
15126 // lexical context will be different from the semantic context.
15127 New->setLexicalDeclContext(CurContext);
15128
15129 // Mark this as a friend decl if applicable.
15130 // In Microsoft mode, a friend declaration also acts as a forward
15131 // declaration so we always pass true to setObjectOfFriendDecl to make
15132 // the tag name visible.
15133 if (TUK == TUK_Friend)
15134 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15135
15136 // Set the access specifier.
15137 if (!Invalid && SearchDC->isRecord())
15138 SetMemberAccessSpecifier(New, PrevDecl, AS);
15139
15140 if (PrevDecl)
15141 CheckRedeclarationModuleOwnership(New, PrevDecl);
15142
15143 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15144 New->startDefinition();
15145
15146 ProcessDeclAttributeList(S, New, Attrs);
15147 AddPragmaAttributes(S, New);
15148
15149 // If this has an identifier, add it to the scope stack.
15150 if (TUK == TUK_Friend) {
15151 // We might be replacing an existing declaration in the lookup tables;
15152 // if so, borrow its access specifier.
15153 if (PrevDecl)
15154 New->setAccess(PrevDecl->getAccess());
15155
15156 DeclContext *DC = New->getDeclContext()->getRedeclContext();
15157 DC->makeDeclVisibleInContext(New);
15158 if (Name) // can be null along some error paths
15159 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15160 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15161 } else if (Name) {
15162 S = getNonFieldDeclScope(S);
15163 PushOnScopeChains(New, S, true);
15164 } else {
15165 CurContext->addDecl(New);
15166 }
15167
15168 // If this is the C FILE type, notify the AST context.
15169 if (IdentifierInfo *II = New->getIdentifier())
15170 if (!New->isInvalidDecl() &&
15171 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15172 II->isStr("FILE"))
15173 Context.setFILEDecl(New);
15174
15175 if (PrevDecl)
15176 mergeDeclAttributes(New, PrevDecl);
15177
15178 // If there's a #pragma GCC visibility in scope, set the visibility of this
15179 // record.
15180 AddPushedVisibilityAttribute(New);
15181
15182 if (isMemberSpecialization && !New->isInvalidDecl())
15183 CompleteMemberSpecialization(New, Previous);
15184
15185 OwnedDecl = true;
15186 // In C++, don't return an invalid declaration. We can't recover well from
15187 // the cases where we make the type anonymous.
15188 if (Invalid && getLangOpts().CPlusPlus) {
15189 if (New->isBeingDefined())
15190 if (auto RD = dyn_cast<RecordDecl>(New))
15191 RD->completeDefinition();
15192 return nullptr;
15193 } else if (SkipBody && SkipBody->ShouldSkip) {
15194 return SkipBody->Previous;
15195 } else {
15196 return New;
15197 }
15198}
15199
15200void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15201 AdjustDeclIfTemplate(TagD);
15202 TagDecl *Tag = cast<TagDecl>(TagD);
15203
15204 // Enter the tag context.
15205 PushDeclContext(S, Tag);
15206
15207 ActOnDocumentableDecl(TagD);
15208
15209 // If there's a #pragma GCC visibility in scope, set the visibility of this
15210 // record.
15211 AddPushedVisibilityAttribute(Tag);
15212}
15213
15214bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15215 SkipBodyInfo &SkipBody) {
15216 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15217 return false;
15218
15219 // Make the previous decl visible.
15220 makeMergedDefinitionVisible(SkipBody.Previous);
15221 return true;
15222}
15223
15224Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15225 assert(isa<ObjCContainerDecl>(IDecl) &&
15226 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15227 DeclContext *OCD = cast<DeclContext>(IDecl);
15228 assert(getContainingDC(OCD) == CurContext &&
15229 "The next DeclContext should be lexically contained in the current one.");
15230 CurContext = OCD;
15231 return IDecl;
15232}
15233
15234void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15235 SourceLocation FinalLoc,
15236 bool IsFinalSpelledSealed,
15237 SourceLocation LBraceLoc) {
15238 AdjustDeclIfTemplate(TagD);
15239 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15240
15241 FieldCollector->StartClass();
15242
15243 if (!Record->getIdentifier())
15244 return;
15245
15246 if (FinalLoc.isValid())
15247 Record->addAttr(new (Context)
15248 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15249
15250 // C++ [class]p2:
15251 // [...] The class-name is also inserted into the scope of the
15252 // class itself; this is known as the injected-class-name. For
15253 // purposes of access checking, the injected-class-name is treated
15254 // as if it were a public member name.
15255 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15256 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15257 Record->getLocation(), Record->getIdentifier(),
15258 /*PrevDecl=*/nullptr,
15259 /*DelayTypeCreation=*/true);
15260 Context.getTypeDeclType(InjectedClassName, Record);
15261 InjectedClassName->setImplicit();
15262 InjectedClassName->setAccess(AS_public);
15263 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15264 InjectedClassName->setDescribedClassTemplate(Template);
15265 PushOnScopeChains(InjectedClassName, S);
15266 assert(InjectedClassName->isInjectedClassName() &&
15267 "Broken injected-class-name");
15268}
15269
15270void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15271 SourceRange BraceRange) {
15272 AdjustDeclIfTemplate(TagD);
15273 TagDecl *Tag = cast<TagDecl>(TagD);
15274 Tag->setBraceRange(BraceRange);
15275
15276 // Make sure we "complete" the definition even it is invalid.
15277 if (Tag->isBeingDefined()) {
15278 assert(Tag->isInvalidDecl() && "We should already have completed it");
15279 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15280 RD->completeDefinition();
15281 }
15282
15283 if (isa<CXXRecordDecl>(Tag)) {
15284 FieldCollector->FinishClass();
15285 }
15286
15287 // Exit this scope of this tag's definition.
15288 PopDeclContext();
15289
15290 if (getCurLexicalContext()->isObjCContainer() &&
15291 Tag->getDeclContext()->isFileContext())
15292 Tag->setTopLevelDeclInObjCContainer();
15293
15294 // Notify the consumer that we've defined a tag.
15295 if (!Tag->isInvalidDecl()) {
15296 Consumer.HandleTagDeclDefinition(Tag);
15297 // Don't try to compute excess padding (which can be expensive) if the diag
15298 // is ignored.
15299 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15300 if (!RD->isDependentContext() && !Diags.isIgnored(diag::warn_excess_padding, RD->getLocation())) {
15301 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
15302 unsigned NumFields = 0;
15303 unsigned LastFieldEnd = 0;
15304 unsigned Padding = 0;
15305 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
15306 unsigned BitEnd = 0;
15307 for (auto F : RD->fields()) {
15308 unsigned Offset = Layout.getFieldOffset(NumFields);
15309 NumFields++;
15310 // Count the bits in a bitfield.
15311 if (F->isBitField()) {
15312 BitEnd += F->getBitWidthValue(Context);
15313 continue;
15314 }
15315 // If the last field was a bitfield then round the width up to a char
15316 // and use that.
15317 if (BitEnd) {
15318 LastFieldEnd += (BitEnd + (CharBitNum - 1)) / CharBitNum;
15319 BitEnd = 0;
15320 }
15321 Padding += Offset - LastFieldEnd;
15322 LastFieldEnd = Offset + Context.getTypeSizeInChars(F->getType()).getQuantity();
15323 }
15324 unsigned Size = Layout.getSize().getQuantity();
15325 Padding += Size - LastFieldEnd;
15326 unsigned UnpaddedSize = Size - Padding;
15327
15328 // Don't warn for empty structs even though they have 1 byte padding in
15329 // a 1 byte record
15330 if (NumFields > 0)
15331 if ((Padding > 8) || ((Padding * 3) > (UnpaddedSize * 4)))
15332 getDiagnostics().Report(RD->getLocation(),
15333 diag::warn_excess_padding)
15334 << Context.getTypeDeclType(RD) << Padding << Size;
15335 }
15336 }
15337}
15338
15339void Sema::ActOnObjCContainerFinishDefinition() {
15340 // Exit this scope of this interface definition.
15341 PopDeclContext();
15342}
15343
15344void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15345 assert(DC == CurContext && "Mismatch of container contexts");
15346 OriginalLexicalContext = DC;
15347 ActOnObjCContainerFinishDefinition();
15348}
15349
15350void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15351 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15352 OriginalLexicalContext = nullptr;
15353}
15354
15355void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15356 AdjustDeclIfTemplate(TagD);
15357 TagDecl *Tag = cast<TagDecl>(TagD);
15358 Tag->setInvalidDecl();
15359
15360 // Make sure we "complete" the definition even it is invalid.
15361 if (Tag->isBeingDefined()) {
15362 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15363 RD->completeDefinition();
15364 }
15365
15366 // We're undoing ActOnTagStartDefinition here, not
15367 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15368 // the FieldCollector.
15369
15370 PopDeclContext();
15371}
15372
15373// Note that FieldName may be null for anonymous bitfields.
15374ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15375 IdentifierInfo *FieldName,
15376 QualType FieldTy, bool IsMsStruct,
15377 Expr *BitWidth, bool *ZeroWidth) {
15378 // Default to true; that shouldn't confuse checks for emptiness
15379 if (ZeroWidth)
15380 *ZeroWidth = true;
15381
15382 // C99 6.7.2.1p4 - verify the field type.
15383 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15384 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15385 // Handle incomplete types with specific error.
15386 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15387 return ExprError();
15388 if (FieldName)
15389 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15390 << FieldName << FieldTy << BitWidth->getSourceRange();
15391 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15392 << FieldTy << BitWidth->getSourceRange();
15393 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15394 UPPC_BitFieldWidth))
15395 return ExprError();
15396
15397 // If the bit-width is type- or value-dependent, don't try to check
15398 // it now.
15399 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15400 return BitWidth;
15401
15402 llvm::APSInt Value;
15403 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15404 if (ICE.isInvalid())
15405 return ICE;
15406 BitWidth = ICE.get();
15407
15408 if (Value != 0 && ZeroWidth)
15409 *ZeroWidth = false;
15410
15411 // Zero-width bitfield is ok for anonymous field.
15412 if (Value == 0 && FieldName)
15413 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15414
15415 if (Value.isSigned() && Value.isNegative()) {
15416 if (FieldName)
15417 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15418 << FieldName << Value.toString(10);
15419 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15420 << Value.toString(10);
15421 }
15422
15423 if (!FieldTy->isDependentType()) {
15424 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15425 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15426 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15427
15428 // Over-wide bitfields are an error in C or when using the MSVC bitfield
15429 // ABI.
15430 bool CStdConstraintViolation =
15431 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15432 bool MSBitfieldViolation =
15433 Value.ugt(TypeStorageSize) &&
15434 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15435 if (CStdConstraintViolation || MSBitfieldViolation) {
15436 unsigned DiagWidth =
15437 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15438 if (FieldName)
15439 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15440 << FieldName << (unsigned)Value.getZExtValue()
15441 << !CStdConstraintViolation << DiagWidth;
15442
15443 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15444 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15445 << DiagWidth;
15446 }
15447
15448 // Warn on types where the user might conceivably expect to get all
15449 // specified bits as value bits: that's all integral types other than
15450 // 'bool'.
15451 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15452 if (FieldName)
15453 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15454 << FieldName << (unsigned)Value.getZExtValue()
15455 << (unsigned)TypeWidth;
15456 else
15457 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15458 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15459 }
15460 }
15461
15462 return BitWidth;
15463}
15464
15465/// ActOnField - Each field of a C struct/union is passed into this in order
15466/// to create a FieldDecl object for it.
15467Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15468 Declarator &D, Expr *BitfieldWidth) {
15469 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15470 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15471 /*InitStyle=*/ICIS_NoInit, AS_public);
15472 return Res;
15473}
15474
15475/// HandleField - Analyze a field of a C struct or a C++ data member.
15476///
15477FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15478 SourceLocation DeclStart,
15479 Declarator &D, Expr *BitWidth,
15480 InClassInitStyle InitStyle,
15481 AccessSpecifier AS) {
15482 if (D.isDecompositionDeclarator()) {
15483 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15484 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15485 << Decomp.getSourceRange();
15486 return nullptr;
15487 }
15488
15489 IdentifierInfo *II = D.getIdentifier();
15490 SourceLocation Loc = DeclStart;
15491 if (II) Loc = D.getIdentifierLoc();
15492
15493 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15494 QualType T = TInfo->getType();
15495 if (getLangOpts().CPlusPlus) {
15496 CheckExtraCXXDefaultArguments(D);
15497
15498 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15499 UPPC_DataMemberType)) {
15500 D.setInvalidType();
15501 T = Context.IntTy;
15502 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15503 }
15504 }
15505
15506 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15507
15508 if (D.getDeclSpec().isInlineSpecified())
15509 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15510 << getLangOpts().CPlusPlus17;
15511 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15512 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15513 diag::err_invalid_thread)
15514 << DeclSpec::getSpecifierName(TSCS);
15515
15516 // Check to see if this name was declared as a member previously
15517 NamedDecl *PrevDecl = nullptr;
15518 LookupResult Previous(*this, II, Loc, LookupMemberName,
15519 ForVisibleRedeclaration);
15520 LookupName(Previous, S);
15521 switch (Previous.getResultKind()) {
15522 case LookupResult::Found:
15523 case LookupResult::FoundUnresolvedValue:
15524 PrevDecl = Previous.getAsSingle<NamedDecl>();
15525 break;
15526
15527 case LookupResult::FoundOverloaded:
15528 PrevDecl = Previous.getRepresentativeDecl();
15529 break;
15530
15531 case LookupResult::NotFound:
15532 case LookupResult::NotFoundInCurrentInstantiation:
15533 case LookupResult::Ambiguous:
15534 break;
15535 }
15536 Previous.suppressDiagnostics();
15537
15538 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15539 // Maybe we will complain about the shadowed template parameter.
15540 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15541 // Just pretend that we didn't see the previous declaration.
15542 PrevDecl = nullptr;
15543 }
15544
15545 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15546 PrevDecl = nullptr;
15547
15548 bool Mutable
15549 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15550 SourceLocation TSSL = D.getBeginLoc();
15551 FieldDecl *NewFD
15552 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15553 TSSL, AS, PrevDecl, &D);
15554
15555 if (NewFD->isInvalidDecl())
15556 Record->setInvalidDecl();
15557
15558 if (D.getDeclSpec().isModulePrivateSpecified())
15559 NewFD->setModulePrivate();
15560
15561 if (NewFD->isInvalidDecl() && PrevDecl) {
15562 // Don't introduce NewFD into scope; there's already something
15563 // with the same name in the same scope.
15564 } else if (II) {
15565 PushOnScopeChains(NewFD, S);
15566 } else
15567 Record->addDecl(NewFD);
15568
15569 return NewFD;
15570}
15571
15572/// Build a new FieldDecl and check its well-formedness.
15573///
15574/// This routine builds a new FieldDecl given the fields name, type,
15575/// record, etc. \p PrevDecl should refer to any previous declaration
15576/// with the same name and in the same scope as the field to be
15577/// created.
15578///
15579/// \returns a new FieldDecl.
15580///
15581/// \todo The Declarator argument is a hack. It will be removed once
15582FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15583 TypeSourceInfo *TInfo,
15584 RecordDecl *Record, SourceLocation Loc,
15585 bool Mutable, Expr *BitWidth,
15586 InClassInitStyle InitStyle,
15587 SourceLocation TSSL,
15588 AccessSpecifier AS, NamedDecl *PrevDecl,
15589 Declarator *D) {
15590 IdentifierInfo *II = Name.getAsIdentifierInfo();
15591 bool InvalidDecl = false;
15592 if (D) InvalidDecl = D->isInvalidType();
15593
15594 // If we receive a broken type, recover by assuming 'int' and
15595 // marking this declaration as invalid.
15596 if (T.isNull()) {
15597 InvalidDecl = true;
15598 T = Context.IntTy;
15599 }
15600
15601 QualType EltTy = Context.getBaseElementType(T);
15602 if (!EltTy->isDependentType()) {
15603 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15604 // Fields of incomplete type force their record to be invalid.
15605 Record->setInvalidDecl();
15606 InvalidDecl = true;
15607 } else {
15608 NamedDecl *Def;
15609 EltTy->isIncompleteType(&Def);
15610 if (Def && Def->isInvalidDecl()) {
15611 Record->setInvalidDecl();
15612 InvalidDecl = true;
15613 }
15614 }
15615 }
15616
15617 // TR 18037 does not allow fields to be declared with address space
15618 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15619 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15620 Diag(Loc, diag::err_field_with_address_space);
15621 Record->setInvalidDecl();
15622 InvalidDecl = true;
15623 }
15624
15625 if (LangOpts.OpenCL) {
15626 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15627 // used as structure or union field: image, sampler, event or block types.
15628 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15629 T->isBlockPointerType()) {
15630 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15631 Record->setInvalidDecl();
15632 InvalidDecl = true;
15633 }
15634 // OpenCL v1.2 s6.9.c: bitfields are not supported.
15635 if (BitWidth) {
15636 Diag(Loc, diag::err_opencl_bitfields);
15637 InvalidDecl = true;
15638 }
15639 }
15640
15641 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15642 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15643 T.hasQualifiers()) {
15644 InvalidDecl = true;
15645 Diag(Loc, diag::err_anon_bitfield_qualifiers);
15646 }
15647
15648 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15649 // than a variably modified type.
15650 if (!InvalidDecl && T->isVariablyModifiedType()) {
15651 bool SizeIsNegative;
15652 llvm::APSInt Oversized;
15653
15654 TypeSourceInfo *FixedTInfo =
15655 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15656 SizeIsNegative,
15657 Oversized);
15658 if (FixedTInfo) {
15659 Diag(Loc, diag::warn_illegal_constant_array_size);
15660 TInfo = FixedTInfo;
15661 T = FixedTInfo->getType();
15662 } else {
15663 if (SizeIsNegative)
15664 Diag(Loc, diag::err_typecheck_negative_array_size);
15665 else if (Oversized.getBoolValue())
15666 Diag(Loc, diag::err_array_too_large)
15667 << Oversized.toString(10);
15668 else
15669 Diag(Loc, diag::err_typecheck_field_variable_size);
15670 InvalidDecl = true;
15671 }
15672 }
15673
15674 // Fields can not have abstract class types
15675 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15676 diag::err_abstract_type_in_decl,
15677 AbstractFieldType))
15678 InvalidDecl = true;
15679
15680 bool ZeroWidth = false;
15681 if (InvalidDecl)
15682 BitWidth = nullptr;
15683 // If this is declared as a bit-field, check the bit-field.
15684 if (BitWidth) {
15685 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15686 &ZeroWidth).get();
15687 if (!BitWidth) {
15688 InvalidDecl = true;
15689 BitWidth = nullptr;
15690 ZeroWidth = false;
15691 }
15692 }
15693
15694 // Check that 'mutable' is consistent with the type of the declaration.
15695 if (!InvalidDecl && Mutable) {
15696 unsigned DiagID = 0;
15697 if (T->isReferenceType())
15698 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15699 : diag::err_mutable_reference;
15700 else if (T.isConstQualified())
15701 DiagID = diag::err_mutable_const;
15702
15703 if (DiagID) {
15704 SourceLocation ErrLoc = Loc;
15705 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15706 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15707 Diag(ErrLoc, DiagID);
15708 if (DiagID != diag::ext_mutable_reference) {
15709 Mutable = false;
15710 InvalidDecl = true;
15711 }
15712 }
15713 }
15714
15715 // C++11 [class.union]p8 (DR1460):
15716 // At most one variant member of a union may have a
15717 // brace-or-equal-initializer.
15718 if (InitStyle != ICIS_NoInit)
15719 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15720
15721 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15722 BitWidth, Mutable, InitStyle);
15723 if (InvalidDecl)
15724 NewFD->setInvalidDecl();
15725
15726 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15727 Diag(Loc, diag::err_duplicate_member) << II;
15728 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15729 NewFD->setInvalidDecl();
15730 }
15731
15732 if (!InvalidDecl && getLangOpts().CPlusPlus) {
15733 if (Record->isUnion()) {
15734 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15735 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15736 if (RDecl->getDefinition()) {
15737 // C++ [class.union]p1: An object of a class with a non-trivial
15738 // constructor, a non-trivial copy constructor, a non-trivial
15739 // destructor, or a non-trivial copy assignment operator
15740 // cannot be a member of a union, nor can an array of such
15741 // objects.
15742 if (CheckNontrivialField(NewFD))
15743 NewFD->setInvalidDecl();
15744 }
15745 }
15746
15747 // C++ [class.union]p1: If a union contains a member of reference type,
15748 // the program is ill-formed, except when compiling with MSVC extensions
15749 // enabled.
15750 if (EltTy->isReferenceType()) {
15751 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15752 diag::ext_union_member_of_reference_type :
15753 diag::err_union_member_of_reference_type)
15754 << NewFD->getDeclName() << EltTy;
15755 if (!getLangOpts().MicrosoftExt)
15756 NewFD->setInvalidDecl();
15757 }
15758 }
15759 }
15760
15761 // FIXME: We need to pass in the attributes given an AST
15762 // representation, not a parser representation.
15763 if (D) {
15764 // FIXME: The current scope is almost... but not entirely... correct here.
15765 ProcessDeclAttributes(getCurScope(), NewFD, *D);
15766
15767 if (NewFD->hasAttrs())
15768 CheckAlignasUnderalignment(NewFD);
15769 }
15770
15771 // In auto-retain/release, infer strong retension for fields of
15772 // retainable type.
15773 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15774 NewFD->setInvalidDecl();
15775
15776 if (T.isObjCGCWeak())
15777 Diag(Loc, diag::warn_attribute_weak_on_field);
15778
15779 NewFD->setAccess(AS);
15780 return NewFD;
15781}
15782
15783bool Sema::CheckNontrivialField(FieldDecl *FD) {
15784 assert(FD);
15785 assert(getLangOpts().CPlusPlus && "valid check only for C++");
15786
15787 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15788 return false;
15789
15790 QualType EltTy = Context.getBaseElementType(FD->getType());
15791 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15792 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15793 if (RDecl->getDefinition()) {
15794 // We check for copy constructors before constructors
15795 // because otherwise we'll never get complaints about
15796 // copy constructors.
15797
15798 CXXSpecialMember member = CXXInvalid;
15799 // We're required to check for any non-trivial constructors. Since the
15800 // implicit default constructor is suppressed if there are any
15801 // user-declared constructors, we just need to check that there is a
15802 // trivial default constructor and a trivial copy constructor. (We don't
15803 // worry about move constructors here, since this is a C++98 check.)
15804 if (RDecl->hasNonTrivialCopyConstructor())
15805 member = CXXCopyConstructor;
15806 else if (!RDecl->hasTrivialDefaultConstructor())
15807 member = CXXDefaultConstructor;
15808 else if (RDecl->hasNonTrivialCopyAssignment())
15809 member = CXXCopyAssignment;
15810 else if (RDecl->hasNonTrivialDestructor())
15811 member = CXXDestructor;
15812
15813 if (member != CXXInvalid) {
15814 if (!getLangOpts().CPlusPlus11 &&
15815 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15816 // Objective-C++ ARC: it is an error to have a non-trivial field of
15817 // a union. However, system headers in Objective-C programs
15818 // occasionally have Objective-C lifetime objects within unions,
15819 // and rather than cause the program to fail, we make those
15820 // members unavailable.
15821 SourceLocation Loc = FD->getLocation();
15822 if (getSourceManager().isInSystemHeader(Loc)) {
15823 if (!FD->hasAttr<UnavailableAttr>())
15824 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15825 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15826 return false;
15827 }
15828 }
15829
15830 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15831 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15832 diag::err_illegal_union_or_anon_struct_member)
15833 << FD->getParent()->isUnion() << FD->getDeclName() << member;
15834 DiagnoseNontrivial(RDecl, member);
15835 return !getLangOpts().CPlusPlus11;
15836 }
15837 }
15838 }
15839
15840 return false;
15841}
15842
15843/// TranslateIvarVisibility - Translate visibility from a token ID to an
15844/// AST enum value.
15845static ObjCIvarDecl::AccessControl
15846TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15847 switch (ivarVisibility) {
15848 default: llvm_unreachable("Unknown visitibility kind");
15849 case tok::objc_private: return ObjCIvarDecl::Private;
15850 case tok::objc_public: return ObjCIvarDecl::Public;
15851 case tok::objc_protected: return ObjCIvarDecl::Protected;
15852 case tok::objc_package: return ObjCIvarDecl::Package;
15853 }
15854}
15855
15856/// ActOnIvar - Each ivar field of an objective-c class is passed into this
15857/// in order to create an IvarDecl object for it.
15858Decl *Sema::ActOnIvar(Scope *S,
15859 SourceLocation DeclStart,
15860 Declarator &D, Expr *BitfieldWidth,
15861 tok::ObjCKeywordKind Visibility) {
15862
15863 IdentifierInfo *II = D.getIdentifier();
15864 Expr *BitWidth = (Expr*)BitfieldWidth;
15865 SourceLocation Loc = DeclStart;
15866 if (II) Loc = D.getIdentifierLoc();
15867
15868 // FIXME: Unnamed fields can be handled in various different ways, for
15869 // example, unnamed unions inject all members into the struct namespace!
15870
15871 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15872 QualType T = TInfo->getType();
15873
15874 if (BitWidth) {
15875 // 6.7.2.1p3, 6.7.2.1p4
15876 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15877 if (!BitWidth)
15878 D.setInvalidType();
15879 } else {
15880 // Not a bitfield.
15881
15882 // validate II.
15883
15884 }
15885 if (T->isReferenceType()) {
15886 Diag(Loc, diag::err_ivar_reference_type);
15887 D.setInvalidType();
15888 }
15889 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15890 // than a variably modified type.
15891 else if (T->isVariablyModifiedType()) {
15892 Diag(Loc, diag::err_typecheck_ivar_variable_size);
15893 D.setInvalidType();
15894 }
15895
15896 // Get the visibility (access control) for this ivar.
15897 ObjCIvarDecl::AccessControl ac =
15898 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15899 : ObjCIvarDecl::None;
15900 // Must set ivar's DeclContext to its enclosing interface.
15901 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15902 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15903 return nullptr;
15904 ObjCContainerDecl *EnclosingContext;
15905 if (ObjCImplementationDecl *IMPDecl =
15906 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15907 if (LangOpts.ObjCRuntime.isFragile()) {
15908 // Case of ivar declared in an implementation. Context is that of its class.
15909 EnclosingContext = IMPDecl->getClassInterface();
15910 assert(EnclosingContext && "Implementation has no class interface!");
15911 }
15912 else
15913 EnclosingContext = EnclosingDecl;
15914 } else {
15915 if (ObjCCategoryDecl *CDecl =
15916 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15917 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15918 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15919 return nullptr;
15920 }
15921 }
15922 EnclosingContext = EnclosingDecl;
15923 }
15924
15925 // Construct the decl.
15926 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15927 DeclStart, Loc, II, T,
15928 TInfo, ac, (Expr *)BitfieldWidth);
15929
15930 if (II) {
15931 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15932 ForVisibleRedeclaration);
15933 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15934 && !isa<TagDecl>(PrevDecl)) {
15935 Diag(Loc, diag::err_duplicate_member) << II;
15936 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15937 NewID->setInvalidDecl();
15938 }
15939 }
15940
15941 // Process attributes attached to the ivar.
15942 ProcessDeclAttributes(S, NewID, D);
15943
15944 if (D.isInvalidType())
15945 NewID->setInvalidDecl();
15946
15947 // In ARC, infer 'retaining' for ivars of retainable type.
15948 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15949 NewID->setInvalidDecl();
15950
15951 if (D.getDeclSpec().isModulePrivateSpecified())
15952 NewID->setModulePrivate();
15953
15954 if (II) {
15955 // FIXME: When interfaces are DeclContexts, we'll need to add
15956 // these to the interface.
15957 S->AddDecl(NewID);
15958 IdResolver.AddDecl(NewID);
15959 }
15960
15961 if (LangOpts.ObjCRuntime.isNonFragile() &&
15962 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15963 Diag(Loc, diag::warn_ivars_in_interface);
15964
15965 return NewID;
15966}
15967
15968/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15969/// class and class extensions. For every class \@interface and class
15970/// extension \@interface, if the last ivar is a bitfield of any type,
15971/// then add an implicit `char :0` ivar to the end of that interface.
15972void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15973 SmallVectorImpl<Decl *> &AllIvarDecls) {
15974 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15975 return;
15976
15977 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15978 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15979
15980 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15981 return;
15982 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15983 if (!ID) {
15984 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15985 if (!CD->IsClassExtension())
15986 return;
15987 }
15988 // No need to add this to end of @implementation.
15989 else
15990 return;
15991 }
15992 // All conditions are met. Add a new bitfield to the tail end of ivars.
15993 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15994 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15995
15996 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15997 DeclLoc, DeclLoc, nullptr,
15998 Context.CharTy,
15999 Context.getTrivialTypeSourceInfo(Context.CharTy,
16000 DeclLoc),
16001 ObjCIvarDecl::Private, BW,
16002 true);
16003 AllIvarDecls.push_back(Ivar);
16004}
16005
16006void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16007 ArrayRef<Decl *> Fields, SourceLocation LBrac,
16008 SourceLocation RBrac,
16009 const ParsedAttributesView &Attrs) {
16010 assert(EnclosingDecl && "missing record or interface decl");
16011
16012 // If this is an Objective-C @implementation or category and we have
16013 // new fields here we should reset the layout of the interface since
16014 // it will now change.
16015 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16016 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16017 switch (DC->getKind()) {
16018 default: break;
16019 case Decl::ObjCCategory:
16020 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16021 break;
16022 case Decl::ObjCImplementation:
16023 Context.
16024 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16025 break;
16026 }
16027 }
16028
16029 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16030 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16031
16032 // Start counting up the number of named members; make sure to include
16033 // members of anonymous structs and unions in the total.
16034 unsigned NumNamedMembers = 0;
16035 if (Record) {
16036 for (const auto *I : Record->decls()) {
16037 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16038 if (IFD->getDeclName())
16039 ++NumNamedMembers;
16040 }
16041 }
16042
16043 // Verify that all the fields are okay.
16044 SmallVector<FieldDecl*, 32> RecFields;
16045
16046 bool ObjCFieldLifetimeErrReported = false;
16047 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16048 i != end; ++i) {
16049 FieldDecl *FD = cast<FieldDecl>(*i);
16050
16051 // Get the type for the field.
16052 const Type *FDTy = FD->getType().getTypePtr();
16053
16054 if (!FD->isAnonymousStructOrUnion()) {
16055 // Remember all fields written by the user.
16056 RecFields.push_back(FD);
16057 }
16058
16059 // If the field is already invalid for some reason, don't emit more
16060 // diagnostics about it.
16061 if (FD->isInvalidDecl()) {
16062 EnclosingDecl->setInvalidDecl();
16063 continue;
16064 }
16065
16066 // C99 6.7.2.1p2:
16067 // A structure or union shall not contain a member with
16068 // incomplete or function type (hence, a structure shall not
16069 // contain an instance of itself, but may contain a pointer to
16070 // an instance of itself), except that the last member of a
16071 // structure with more than one named member may have incomplete
16072 // array type; such a structure (and any union containing,
16073 // possibly recursively, a member that is such a structure)
16074 // shall not be a member of a structure or an element of an
16075 // array.
16076 bool IsLastField = (i + 1 == Fields.end());
16077 if (FDTy->isFunctionType()) {
16078 // Field declared as a function.
16079 Diag(FD->getLocation(), diag::err_field_declared_as_function)
16080 << FD->getDeclName();
16081 FD->setInvalidDecl();
16082 EnclosingDecl->setInvalidDecl();
16083 continue;
16084 } else if (FDTy->isIncompleteArrayType() &&
16085 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16086 if (Record) {
16087 // Flexible array member.
16088 // Microsoft and g++ is more permissive regarding flexible array.
16089 // It will accept flexible array in union and also
16090 // as the sole element of a struct/class.
16091 unsigned DiagID = 0;
16092 if (!Record->isUnion() && !IsLastField) {
16093 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16094 << FD->getDeclName() << FD->getType() << Record->getTagKind();
16095 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16096 FD->setInvalidDecl();
16097 EnclosingDecl->setInvalidDecl();
16098 continue;
16099 } else if (Record->isUnion())
16100 DiagID = getLangOpts().MicrosoftExt
16101 ? diag::ext_flexible_array_union_ms
16102 : getLangOpts().CPlusPlus
16103 ? diag::ext_flexible_array_union_gnu
16104 : diag::err_flexible_array_union;
16105 else if (NumNamedMembers < 1)
16106 DiagID = getLangOpts().MicrosoftExt
16107 ? diag::ext_flexible_array_empty_aggregate_ms
16108 : getLangOpts().CPlusPlus
16109 ? diag::ext_flexible_array_empty_aggregate_gnu
16110 : diag::err_flexible_array_empty_aggregate;
16111
16112 if (DiagID)
16113 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16114 << Record->getTagKind();
16115 // While the layout of types that contain virtual bases is not specified
16116 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16117 // virtual bases after the derived members. This would make a flexible
16118 // array member declared at the end of an object not adjacent to the end
16119 // of the type.
16120 if (CXXRecord && CXXRecord->getNumVBases() != 0)
16121 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16122 << FD->getDeclName() << Record->getTagKind();
16123 if (!getLangOpts().C99)
16124 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16125 << FD->getDeclName() << Record->getTagKind();
16126
16127 // If the element type has a non-trivial destructor, we would not
16128 // implicitly destroy the elements, so disallow it for now.
16129 //
16130 // FIXME: GCC allows this. We should probably either implicitly delete
16131 // the destructor of the containing class, or just allow this.
16132 QualType BaseElem = Context.getBaseElementType(FD->getType());
16133 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16134 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16135 << FD->getDeclName() << FD->getType();
16136 FD->setInvalidDecl();
16137 EnclosingDecl->setInvalidDecl();
16138 continue;
16139 }
16140 // Okay, we have a legal flexible array member at the end of the struct.
16141 Record->setHasFlexibleArrayMember(true);
16142 } else {
16143 // In ObjCContainerDecl ivars with incomplete array type are accepted,
16144 // unless they are followed by another ivar. That check is done
16145 // elsewhere, after synthesized ivars are known.
16146 }
16147 } else if (!FDTy->isDependentType() &&
16148 RequireCompleteType(FD->getLocation(), FD->getType(),
16149 diag::err_field_incomplete)) {
16150 // Incomplete type
16151 FD->setInvalidDecl();
16152 EnclosingDecl->setInvalidDecl();
16153 continue;
16154 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16155 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16156 // A type which contains a flexible array member is considered to be a
16157 // flexible array member.
16158 Record->setHasFlexibleArrayMember(true);
16159 if (!Record->isUnion()) {
16160 // If this is a struct/class and this is not the last element, reject
16161 // it. Note that GCC supports variable sized arrays in the middle of
16162 // structures.
16163 if (!IsLastField)
16164 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16165 << FD->getDeclName() << FD->getType();
16166 else {
16167 // We support flexible arrays at the end of structs in
16168 // other structs as an extension.
16169 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16170 << FD->getDeclName();
16171 }
16172 }
16173 }
16174 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16175 RequireNonAbstractType(FD->getLocation(), FD->getType(),
16176 diag::err_abstract_type_in_decl,
16177 AbstractIvarType)) {
16178 // Ivars can not have abstract class types
16179 FD->setInvalidDecl();
16180 }
16181 if (Record && FDTTy->getDecl()->hasObjectMember())
16182 Record->setHasObjectMember(true);
16183 if (Record && FDTTy->getDecl()->hasVolatileMember())
16184 Record->setHasVolatileMember(true);
16185 if (Record && Record->isUnion() &&
16186 FD->getType().isNonTrivialPrimitiveCType(Context))
16187 Diag(FD->getLocation(),
16188 diag::err_nontrivial_primitive_type_in_union);
16189 } else if (FDTy->isObjCObjectType()) {
16190 /// A field cannot be an Objective-c object
16191 Diag(FD->getLocation(), diag::err_statically_allocated_object)
16192 << FixItHint::CreateInsertion(FD->getLocation(), "*");
16193 QualType T = Context.getObjCObjectPointerType(FD->getType());
16194 FD->setType(T);
16195 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
16196 Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
16197 !getLangOpts().CPlusPlus) {
16198 // It's an error in ARC or Weak if a field has lifetime.
16199 // We don't want to report this in a system header, though,
16200 // so we just make the field unavailable.
16201 // FIXME: that's really not sufficient; we need to make the type
16202 // itself invalid to, say, initialize or copy.
16203 QualType T = FD->getType();
16204 if (T.hasNonTrivialObjCLifetime()) {
16205 SourceLocation loc = FD->getLocation();
16206 if (getSourceManager().isInSystemHeader(loc)) {
16207 if (!FD->hasAttr<UnavailableAttr>()) {
16208 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16209 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
16210 }
16211 } else {
16212 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
16213 << T->isBlockPointerType() << Record->getTagKind();
16214 }
16215 ObjCFieldLifetimeErrReported = true;
16216 }
16217 } else if (getLangOpts().ObjC &&
16218 getLangOpts().getGC() != LangOptions::NonGC &&
16219 Record && !Record->hasObjectMember()) {
16220 if (FD->getType()->isObjCObjectPointerType() ||
16221 FD->getType().isObjCGCStrong())
16222 Record->setHasObjectMember(true);
16223 else if (Context.getAsArrayType(FD->getType())) {
16224 QualType BaseType = Context.getBaseElementType(FD->getType());
16225 if (BaseType->isRecordType() &&
16226 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16227 Record->setHasObjectMember(true);
16228 else if (BaseType->isObjCObjectPointerType() ||
16229 BaseType.isObjCGCStrong())
16230 Record->setHasObjectMember(true);
16231 }
16232 }
16233
16234 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16235 QualType FT = FD->getType();
16236 if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16237 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16238 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16239 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16240 Record->setNonTrivialToPrimitiveCopy(true);
16241 if (FT.isDestructedType()) {
16242 Record->setNonTrivialToPrimitiveDestroy(true);
16243 Record->setParamDestroyedInCallee(true);
16244 }
16245
16246 if (const auto *RT = FT->getAs<RecordType>()) {
16247 if (RT->getDecl()->getArgPassingRestrictions() ==
16248 RecordDecl::APK_CanNeverPassInRegs)
16249 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16250 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16251 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16252 }
16253
16254 if (Record && FD->getType().isVolatileQualified())
16255 Record->setHasVolatileMember(true);
16256 // Keep track of the number of named members.
16257 if (FD->getIdentifier())
16258 ++NumNamedMembers;
16259 }
16260
16261 // Okay, we successfully defined 'Record'.
16262 if (Record) {
16263 bool Completed = false;
16264 if (CXXRecord) {
16265 if (!CXXRecord->isInvalidDecl()) {
16266 // Set access bits correctly on the directly-declared conversions.
16267 for (CXXRecordDecl::conversion_iterator
16268 I = CXXRecord->conversion_begin(),
16269 E = CXXRecord->conversion_end(); I != E; ++I)
16270 I.setAccess((*I)->getAccess());
16271 }
16272
16273 if (!CXXRecord->isDependentType()) {
16274 // Add any implicitly-declared members to this class.
16275 AddImplicitlyDeclaredMembersToClass(CXXRecord);
16276
16277 if (!CXXRecord->isInvalidDecl()) {
16278 // If we have virtual base classes, we may end up finding multiple
16279 // final overriders for a given virtual function. Check for this
16280 // problem now.
16281 if (CXXRecord->getNumVBases()) {
16282 CXXFinalOverriderMap FinalOverriders;
16283 CXXRecord->getFinalOverriders(FinalOverriders);
16284
16285 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16286 MEnd = FinalOverriders.end();
16287 M != MEnd; ++M) {
16288 for (OverridingMethods::iterator SO = M->second.begin(),
16289 SOEnd = M->second.end();
16290 SO != SOEnd; ++SO) {
16291 assert(SO->second.size() > 0 &&
16292 "Virtual function without overriding functions?");
16293 if (SO->second.size() == 1)
16294 continue;
16295
16296 // C++ [class.virtual]p2:
16297 // In a derived class, if a virtual member function of a base
16298 // class subobject has more than one final overrider the
16299 // program is ill-formed.
16300 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16301 << (const NamedDecl *)M->first << Record;
16302 Diag(M->first->getLocation(),
16303 diag::note_overridden_virtual_function);
16304 for (OverridingMethods::overriding_iterator
16305 OM = SO->second.begin(),
16306 OMEnd = SO->second.end();
16307 OM != OMEnd; ++OM)
16308 Diag(OM->Method->getLocation(), diag::note_final_overrider)
16309 << (const NamedDecl *)M->first << OM->Method->getParent();
16310
16311 Record->setInvalidDecl();
16312 }
16313 }
16314 CXXRecord->completeDefinition(&FinalOverriders);
16315 Completed = true;
16316 }
16317 }
16318 }
16319 }
16320
16321 if (!Completed)
16322 Record->completeDefinition();
16323
16324 // Handle attributes before checking the layout.
16325 ProcessDeclAttributeList(S, Record, Attrs);
16326
16327 // We may have deferred checking for a deleted destructor. Check now.
16328 if (CXXRecord) {
16329 auto *Dtor = CXXRecord->getDestructor();
16330 if (Dtor && Dtor->isImplicit() &&
16331 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16332 CXXRecord->setImplicitDestructorIsDeleted();
16333 SetDeclDeleted(Dtor, CXXRecord->getLocation());
16334 }
16335 }
16336
16337 if (Record->hasAttrs()) {
16338 CheckAlignasUnderalignment(Record);
16339
16340 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16341 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16342 IA->getRange(), IA->getBestCase(),
16343 IA->getSemanticSpelling());
16344 }
16345
16346 // Check if the structure/union declaration is a type that can have zero
16347 // size in C. For C this is a language extension, for C++ it may cause
16348 // compatibility problems.
16349 bool CheckForZeroSize;
16350 if (!getLangOpts().CPlusPlus) {
16351 CheckForZeroSize = true;
16352 } else {
16353 // For C++ filter out types that cannot be referenced in C code.
16354 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16355 CheckForZeroSize =
16356 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16357 !CXXRecord->isDependentType() &&
16358 CXXRecord->isCLike();
16359 }
16360 if (CheckForZeroSize) {
16361 bool ZeroSize = true;
16362 bool IsEmpty = true;
16363 unsigned NonBitFields = 0;
16364 for (RecordDecl::field_iterator I = Record->field_begin(),
16365 E = Record->field_end();
16366 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16367 IsEmpty = false;
16368 if (I->isUnnamedBitfield()) {
16369 if (!I->isZeroLengthBitField(Context))
16370 ZeroSize = false;
16371 } else {
16372 ++NonBitFields;
16373 QualType FieldType = I->getType();
16374 if (FieldType->isIncompleteType() ||
16375 !Context.getTypeSizeInChars(FieldType).isZero())
16376 ZeroSize = false;
16377 }
16378 }
16379
16380 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16381 // allowed in C++, but warn if its declaration is inside
16382 // extern "C" block.
16383 if (ZeroSize) {
16384 Diag(RecLoc, getLangOpts().CPlusPlus ?
16385 diag::warn_zero_size_struct_union_in_extern_c :
16386 diag::warn_zero_size_struct_union_compat)
16387 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16388 }
16389
16390 // Structs without named members are extension in C (C99 6.7.2.1p7),
16391 // but are accepted by GCC.
16392 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16393 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16394 diag::ext_no_named_members_in_struct_union)
16395 << Record->isUnion();
16396 }
16397 }
16398 } else {
16399 ObjCIvarDecl **ClsFields =
16400 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16401 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16402 ID->setEndOfDefinitionLoc(RBrac);
16403 // Add ivar's to class's DeclContext.
16404 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16405 ClsFields[i]->setLexicalDeclContext(ID);
16406 ID->addDecl(ClsFields[i]);
16407 }
16408 // Must enforce the rule that ivars in the base classes may not be
16409 // duplicates.
16410 if (ID->getSuperClass())
16411 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16412 } else if (ObjCImplementationDecl *IMPDecl =
16413 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16414 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16415 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16416 // Ivar declared in @implementation never belongs to the implementation.
16417 // Only it is in implementation's lexical context.
16418 ClsFields[I]->setLexicalDeclContext(IMPDecl);
16419 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16420 IMPDecl->setIvarLBraceLoc(LBrac);
16421 IMPDecl->setIvarRBraceLoc(RBrac);
16422 } else if (ObjCCategoryDecl *CDecl =
16423 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16424 // case of ivars in class extension; all other cases have been
16425 // reported as errors elsewhere.
16426 // FIXME. Class extension does not have a LocEnd field.
16427 // CDecl->setLocEnd(RBrac);
16428 // Add ivar's to class extension's DeclContext.
16429 // Diagnose redeclaration of private ivars.
16430 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16431 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16432 if (IDecl) {
16433 if (const ObjCIvarDecl *ClsIvar =
16434 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16435 Diag(ClsFields[i]->getLocation(),
16436 diag::err_duplicate_ivar_declaration);
16437 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16438 continue;
16439 }
16440 for (const auto *Ext : IDecl->known_extensions()) {
16441 if (const ObjCIvarDecl *ClsExtIvar
16442 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16443 Diag(ClsFields[i]->getLocation(),
16444 diag::err_duplicate_ivar_declaration);
16445 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16446 continue;
16447 }
16448 }
16449 }
16450 ClsFields[i]->setLexicalDeclContext(CDecl);
16451 CDecl->addDecl(ClsFields[i]);
16452 }
16453 CDecl->setIvarLBraceLoc(LBrac);
16454 CDecl->setIvarRBraceLoc(RBrac);
16455 }
16456 }
16457 if (Record && Record->hasAttr<PackedAttr>() && !Record->isDependentType()) {
16458 std::function<bool(const RecordDecl *R)> contains_capabilities =
16459 [&](const RecordDecl *R) {
16460 for (const auto *F : R->fields()) {
16461 auto FTy = F->getType();
16462 if (FTy->isCHERICapabilityType(getASTContext()))
16463 return true;
16464 if (FTy->isRecordType() &&
16465 contains_capabilities(FTy->getAs<RecordType>()->getDecl()))
16466 return true;
16467 }
16468 return false;
16469 };
16470 const FieldDecl *CheckForUseInArray = nullptr;
16471 for (const auto *F : Record->fields()) {
16472 auto FTy = F->getType();
16473 // We shouldn't be calling Context.getTypeAlign() as this alters the
16474 // order in which some Record layouts get initialized and therefore
16475 // breaks CodeGen/override-layout.c and CodeGenCXX/override-layout.cpp
16476 // Context.getDeclAlign() appears to be the correct function to call
16477 // but it will always return 1 byte alignment for fields in a struct
16478 // that has a packed attribute and is only an estimate otherwise (and
16479 // appears to be wrong quite frequently).
16480 // To avoid breaking any existing test cases that depend on the order, we
16481 // make sure to only call getTypeAlign() if the field is actually a
16482 // capability type
16483 auto checkCapabilityFieldAlignment = [&](unsigned DiagID) {
16484 // Calling getTypeAlign on dependent types will fail, so we need to fall
16485 // back to an estimate from GetDeclAlign
16486 unsigned CapAlign = FTy->isDependentType() ?
16487 Context.toBits(Context.getDeclAlign(F)) : Context.getTypeAlign(FTy);
16488 unsigned FieldOffset = Context.getFieldOffset(F);
16489 if (FieldOffset % CapAlign) {
16490 Diag(F->getLocation(), DiagID)
16491 << (unsigned)Context.toCharUnitsFromBits(FieldOffset).getQuantity();
16492 // only check use in array if we haven't diagnosed anything yet
16493 CheckForUseInArray = nullptr;
16494 } else {
16495 CheckForUseInArray = F;
16496 }
16497 };
16498 if (FTy->isCHERICapabilityType(Context)) {
16499 checkCapabilityFieldAlignment(diag::warn_packed_capability);
16500 } else if (FTy->isRecordType() &&
16501 contains_capabilities(FTy->getAs<RecordType>()->getDecl())) {
16502 checkCapabilityFieldAlignment(diag::warn_packed_struct_capability);
16503 }
16504 }
16505 if (CheckForUseInArray) {
16506 assert(!Record->isDependentType());
16507 unsigned RecordAlign = Context.getTypeAlign(Record->getTypeForDecl());
16508 unsigned RecordSize = Context.getTypeSize(Record->getTypeForDecl());
16509 unsigned CapAlign = Context.getTargetInfo().getCHERICapabilityAlign();
16510 // Warn if alignment is not a multiple of CapAlign unless size is a
16511 // multiple of CapAlign
16512 // I.e. struct { char pad[sizeof(void*)]; void* cap; char bad; } __packed
16513 // will cause a warning but
16514 // struct { char pad[sizeof(void*)]; void* cap; } __packed is okay
16515 if ((RecordAlign % CapAlign) && (RecordSize % CapAlign)) {
16516 unsigned AlignBytes = Context.toCharUnitsFromBits(CapAlign).getQuantity();
16517 unsigned FieldOffset = Context.toCharUnitsFromBits(
16518 Context.getFieldOffset(CheckForUseInArray)).getQuantity();
16519 Diag(CheckForUseInArray->getLocation(),
16520 diag::warn_packed_capability_in_array) << FieldOffset;
16521 Diag(Record->getSourceRange().getEnd(),
16522 diag::note_insert_attribute_aligned) << AlignBytes
16523 << FixItHint::CreateInsertion(Record->getSourceRange().getEnd(),
16524 ("__attribute__((aligned(" + Twine(AlignBytes) + ")))").str());
16525 }
16526 }
16527 }
16528}
16529
16530/// Determine whether the given integral value is representable within
16531/// the given type T.
16532static bool isRepresentableIntegerValue(ASTContext &Context,
16533 llvm::APSInt &Value,
16534 QualType T) {
16535 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16536 "Integral type required!");
16537 unsigned BitWidth = Context.getIntWidth(T);
16538
16539 if (Value.isUnsigned() || Value.isNonNegative()) {
16540 if (T->isSignedIntegerOrEnumerationType())
16541 --BitWidth;
16542 return Value.getActiveBits() <= BitWidth;
16543 }
16544 return Value.getMinSignedBits() <= BitWidth;
16545}
16546
16547// Given an integral type, return the next larger integral type
16548// (or a NULL type of no such type exists).
16549static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16550 // FIXME: Int128/UInt128 support, which also needs to be introduced into
16551 // enum checking below.
16552 assert((T->isIntegralType(Context) ||
16553 T->isEnumeralType()) && "Integral type required!");
16554 const unsigned NumTypes = 4;
16555 QualType SignedIntegralTypes[NumTypes] = {
16556 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16557 };
16558 QualType UnsignedIntegralTypes[NumTypes] = {
16559 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16560 Context.UnsignedLongLongTy
16561 };
16562
16563 unsigned BitWidth = Context.getTypeSize(T);
16564 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16565 : UnsignedIntegralTypes;
16566 for (unsigned I = 0; I != NumTypes; ++I)
16567 if (Context.getTypeSize(Types[I]) > BitWidth)
16568 return Types[I];
16569
16570 return QualType();
16571}
16572
16573EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16574 EnumConstantDecl *LastEnumConst,
16575 SourceLocation IdLoc,
16576 IdentifierInfo *Id,
16577 Expr *Val) {
16578 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16579 llvm::APSInt EnumVal(IntWidth);
16580 QualType EltTy;
16581
16582 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16583 Val = nullptr;
16584
16585 if (Val)
16586 Val = DefaultLvalueConversion(Val).get();
16587
16588 if (Val) {
16589 if (Enum->isDependentType() || Val->isTypeDependent())
16590 EltTy = Context.DependentTy;
16591 else {
16592 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16593 !getLangOpts().MSVCCompat) {
16594 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16595 // constant-expression in the enumerator-definition shall be a converted
16596 // constant expression of the underlying type.
16597 EltTy = Enum->getIntegerType();
16598 ExprResult Converted =
16599 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16600 CCEK_Enumerator);
16601 if (Converted.isInvalid())
16602 Val = nullptr;
16603 else
16604 Val = Converted.get();
16605 } else if (!Val->isValueDependent() &&
16606 !(Val = VerifyIntegerConstantExpression(Val,
16607 &EnumVal).get())) {
16608 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16609 } else {
16610 if (Enum->isComplete()) {
16611 EltTy = Enum->getIntegerType();
16612
16613 // In Obj-C and Microsoft mode, require the enumeration value to be
16614 // representable in the underlying type of the enumeration. In C++11,
16615 // we perform a non-narrowing conversion as part of converted constant
16616 // expression checking.
16617 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16618 if (getLangOpts().MSVCCompat) {
16619 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16620 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16621 } else
16622 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16623 } else
16624 Val = ImpCastExprToType(Val, EltTy,
16625 EltTy->isBooleanType() ?
16626 CK_IntegralToBoolean : CK_IntegralCast)
16627 .get();
16628 } else if (getLangOpts().CPlusPlus) {
16629 // C++11 [dcl.enum]p5:
16630 // If the underlying type is not fixed, the type of each enumerator
16631 // is the type of its initializing value:
16632 // - If an initializer is specified for an enumerator, the
16633 // initializing value has the same type as the expression.
16634 EltTy = Val->getType();
16635 } else {
16636 // C99 6.7.2.2p2:
16637 // The expression that defines the value of an enumeration constant
16638 // shall be an integer constant expression that has a value
16639 // representable as an int.
16640
16641 // Complain if the value is not representable in an int.
16642 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16643 Diag(IdLoc, diag::ext_enum_value_not_int)
16644 << EnumVal.toString(10) << Val->getSourceRange()
16645 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16646 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16647 // Force the type of the expression to 'int'.
16648 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16649 }
16650 EltTy = Val->getType();
16651 }
16652 }
16653 }
16654 }
16655
16656 if (!Val) {
16657 if (Enum->isDependentType())
16658 EltTy = Context.DependentTy;
16659 else if (!LastEnumConst) {
16660 // C++0x [dcl.enum]p5:
16661 // If the underlying type is not fixed, the type of each enumerator
16662 // is the type of its initializing value:
16663 // - If no initializer is specified for the first enumerator, the
16664 // initializing value has an unspecified integral type.
16665 //
16666 // GCC uses 'int' for its unspecified integral type, as does
16667 // C99 6.7.2.2p3.
16668 if (Enum->isFixed()) {
16669 EltTy = Enum->getIntegerType();
16670 }
16671 else {
16672 EltTy = Context.IntTy;
16673 }
16674 } else {
16675 // Assign the last value + 1.
16676 EnumVal = LastEnumConst->getInitVal();
16677 ++EnumVal;
16678 EltTy = LastEnumConst->getType();
16679
16680 // Check for overflow on increment.
16681 if (EnumVal < LastEnumConst->getInitVal()) {
16682 // C++0x [dcl.enum]p5:
16683 // If the underlying type is not fixed, the type of each enumerator
16684 // is the type of its initializing value:
16685 //
16686 // - Otherwise the type of the initializing value is the same as
16687 // the type of the initializing value of the preceding enumerator
16688 // unless the incremented value is not representable in that type,
16689 // in which case the type is an unspecified integral type
16690 // sufficient to contain the incremented value. If no such type
16691 // exists, the program is ill-formed.
16692 QualType T = getNextLargerIntegralType(Context, EltTy);
16693 if (T.isNull() || Enum->isFixed()) {
16694 // There is no integral type larger enough to represent this
16695 // value. Complain, then allow the value to wrap around.
16696 EnumVal = LastEnumConst->getInitVal();
16697 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16698 ++EnumVal;
16699 if (Enum->isFixed())
16700 // When the underlying type is fixed, this is ill-formed.
16701 Diag(IdLoc, diag::err_enumerator_wrapped)
16702 << EnumVal.toString(10)
16703 << EltTy;
16704 else
16705 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16706 << EnumVal.toString(10);
16707 } else {
16708 EltTy = T;
16709 }
16710
16711 // Retrieve the last enumerator's value, extent that type to the
16712 // type that is supposed to be large enough to represent the incremented
16713 // value, then increment.
16714 EnumVal = LastEnumConst->getInitVal();
16715 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16716 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16717 ++EnumVal;
16718
16719 // If we're not in C++, diagnose the overflow of enumerator values,
16720 // which in C99 means that the enumerator value is not representable in
16721 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16722 // permits enumerator values that are representable in some larger
16723 // integral type.
16724 if (!getLangOpts().CPlusPlus && !T.isNull())
16725 Diag(IdLoc, diag::warn_enum_value_overflow);
16726 } else if (!getLangOpts().CPlusPlus &&
16727 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16728 // Enforce C99 6.7.2.2p2 even when we compute the next value.
16729 Diag(IdLoc, diag::ext_enum_value_not_int)
16730 << EnumVal.toString(10) << 1;
16731 }
16732 }
16733 }
16734
16735 if (!EltTy->isDependentType()) {
16736 // Make the enumerator value match the signedness and size of the
16737 // enumerator's type.
16738 EnumVal = EnumVal.extOrTrunc(Context.getIntRange(EltTy));
16739 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16740 }
16741
16742 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16743 Val, EnumVal);
16744}
16745
16746Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16747 SourceLocation IILoc) {
16748 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16749 !getLangOpts().CPlusPlus)
16750 return SkipBodyInfo();
16751
16752 // We have an anonymous enum definition. Look up the first enumerator to
16753 // determine if we should merge the definition with an existing one and
16754 // skip the body.
16755 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16756 forRedeclarationInCurContext());
16757 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16758 if (!PrevECD)
16759 return SkipBodyInfo();
16760
16761 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16762 NamedDecl *Hidden;
16763 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16764 SkipBodyInfo Skip;
16765 Skip.Previous = Hidden;
16766 return Skip;
16767 }
16768
16769 return SkipBodyInfo();
16770}
16771
16772Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16773 SourceLocation IdLoc, IdentifierInfo *Id,
16774 const ParsedAttributesView &Attrs,
16775 SourceLocation EqualLoc, Expr *Val) {
16776 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16777 EnumConstantDecl *LastEnumConst =
16778 cast_or_null<EnumConstantDecl>(lastEnumConst);
16779
16780 // The scope passed in may not be a decl scope. Zip up the scope tree until
16781 // we find one that is.
16782 S = getNonFieldDeclScope(S);
16783
16784 // Verify that there isn't already something declared with this name in this
16785 // scope.
16786 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16787 LookupName(R, S);
16788 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16789
16790 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16791 // Maybe we will complain about the shadowed template parameter.
16792 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16793 // Just pretend that we didn't see the previous declaration.
16794 PrevDecl = nullptr;
16795 }
16796
16797 // C++ [class.mem]p15:
16798 // If T is the name of a class, then each of the following shall have a name
16799 // different from T:
16800 // - every enumerator of every member of class T that is an unscoped
16801 // enumerated type
16802 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16803 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16804 DeclarationNameInfo(Id, IdLoc));
16805
16806 EnumConstantDecl *New =
16807 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16808 if (!New)
16809 return nullptr;
16810
16811 if (PrevDecl) {
16812 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16813 // Check for other kinds of shadowing not already handled.
16814 CheckShadow(New, PrevDecl, R);
16815 }
16816
16817 // When in C++, we may get a TagDecl with the same name; in this case the
16818 // enum constant will 'hide' the tag.
16819 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16820 "Received TagDecl when not in C++!");
16821 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16822 if (isa<EnumConstantDecl>(PrevDecl))
16823 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16824 else
16825 Diag(IdLoc, diag::err_redefinition) << Id;
16826 notePreviousDefinition(PrevDecl, IdLoc);
16827 return nullptr;
16828 }
16829 }
16830
16831 // Process attributes.
16832 ProcessDeclAttributeList(S, New, Attrs);
16833 AddPragmaAttributes(S, New);
16834
16835 // Register this decl in the current scope stack.
16836 New->setAccess(TheEnumDecl->getAccess());
16837 PushOnScopeChains(New, S);
16838
16839 ActOnDocumentableDecl(New);
16840
16841 return New;
16842}
16843
16844// Returns true when the enum initial expression does not trigger the
16845// duplicate enum warning. A few common cases are exempted as follows:
16846// Element2 = Element1
16847// Element2 = Element1 + 1
16848// Element2 = Element1 - 1
16849// Where Element2 and Element1 are from the same enum.
16850static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16851 Expr *InitExpr = ECD->getInitExpr();
16852 if (!InitExpr)
16853 return true;
16854 InitExpr = InitExpr->IgnoreImpCasts();
16855
16856 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16857 if (!BO->isAdditiveOp())
16858 return true;
16859 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16860 if (!IL)
16861 return true;
16862 if (IL->getValue() != 1)
16863 return true;
16864
16865 InitExpr = BO->getLHS();
16866 }
16867
16868 // This checks if the elements are from the same enum.
16869 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16870 if (!DRE)
16871 return true;
16872
16873 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16874 if (!EnumConstant)
16875 return true;
16876
16877 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16878 Enum)
16879 return true;
16880
16881 return false;
16882}
16883
16884// Emits a warning when an element is implicitly set a value that
16885// a previous element has already been set to.
16886static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16887 EnumDecl *Enum, QualType EnumType) {
16888 // Avoid anonymous enums
16889 if (!Enum->getIdentifier())
16890 return;
16891
16892 // Only check for small enums.
16893 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16894 return;
16895
16896 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16897 return;
16898
16899 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16900 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16901
16902 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16903 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16904
16905 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16906 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16907 llvm::APSInt Val = D->getInitVal();
16908 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16909 };
16910
16911 DuplicatesVector DupVector;
16912 ValueToVectorMap EnumMap;
16913
16914 // Populate the EnumMap with all values represented by enum constants without
16915 // an initializer.
16916 for (auto *Element : Elements) {
16917 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16918
16919 // Null EnumConstantDecl means a previous diagnostic has been emitted for
16920 // this constant. Skip this enum since it may be ill-formed.
16921 if (!ECD) {
16922 return;
16923 }
16924
16925 // Constants with initalizers are handled in the next loop.
16926 if (ECD->getInitExpr())
16927 continue;
16928
16929 // Duplicate values are handled in the next loop.
16930 EnumMap.insert({EnumConstantToKey(ECD), ECD});
16931 }
16932
16933 if (EnumMap.size() == 0)
16934 return;
16935
16936 // Create vectors for any values that has duplicates.
16937 for (auto *Element : Elements) {
16938 // The last loop returned if any constant was null.
16939 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16940 if (!ValidDuplicateEnum(ECD, Enum))
16941 continue;
16942
16943 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16944 if (Iter == EnumMap.end())
16945 continue;
16946
16947 DeclOrVector& Entry = Iter->second;
16948 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16949 // Ensure constants are different.
16950 if (D == ECD)
16951 continue;
16952
16953 // Create new vector and push values onto it.
16954 auto Vec = llvm::make_unique<ECDVector>();
16955 Vec->push_back(D);
16956 Vec->push_back(ECD);
16957
16958 // Update entry to point to the duplicates vector.
16959 Entry = Vec.get();
16960
16961 // Store the vector somewhere we can consult later for quick emission of
16962 // diagnostics.
16963 DupVector.emplace_back(std::move(Vec));
16964 continue;
16965 }
16966
16967 ECDVector *Vec = Entry.get<ECDVector*>();
16968 // Make sure constants are not added more than once.
16969 if (*Vec->begin() == ECD)
16970 continue;
16971
16972 Vec->push_back(ECD);
16973 }
16974
16975 // Emit diagnostics.
16976 for (const auto &Vec : DupVector) {
16977 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16978
16979 // Emit warning for one enum constant.
16980 auto *FirstECD = Vec->front();
16981 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16982 << FirstECD << FirstECD->getInitVal().toString(10)
16983 << FirstECD->getSourceRange();
16984
16985 // Emit one note for each of the remaining enum constants with
16986 // the same value.
16987 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16988 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16989 << ECD << ECD->getInitVal().toString(10)
16990 << ECD->getSourceRange();
16991 }
16992}
16993
16994bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16995 bool AllowMask) const {
16996 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16997 assert(ED->isCompleteDefinition() && "expected enum definition");
16998
16999 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17000 llvm::APInt &FlagBits = R.first->second;
17001
17002 if (R.second) {
17003 for (auto *E : ED->enumerators()) {
17004 const auto &EVal = E->getInitVal();
17005 // Only single-bit enumerators introduce new flag values.
17006 if (EVal.isPowerOf2())
17007 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17008 }
17009 }
17010
17011 // A value is in a flag enum if either its bits are a subset of the enum's
17012 // flag bits (the first condition) or we are allowing masks and the same is
17013 // true of its complement (the second condition). When masks are allowed, we
17014 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17015 //
17016 // While it's true that any value could be used as a mask, the assumption is
17017 // that a mask will have all of the insignificant bits set. Anything else is
17018 // likely a logic error.
17019 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17020 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17021}
17022
17023void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17024 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17025 const ParsedAttributesView &Attrs) {
17026 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17027 QualType EnumType = Context.getTypeDeclType(Enum);
17028
17029 ProcessDeclAttributeList(S, Enum, Attrs);
17030
17031 if (Enum->isDependentType()) {
17032 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17033 EnumConstantDecl *ECD =
17034 cast_or_null<EnumConstantDecl>(Elements[i]);
17035 if (!ECD) continue;
17036
17037 ECD->setType(EnumType);
17038 }
17039
17040 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17041 return;
17042 }
17043
17044 // TODO: If the result value doesn't fit in an int, it must be a long or long
17045 // long value. ISO C does not support this, but GCC does as an extension,
17046 // emit a warning.
17047 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17048 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17049 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17050
17051 // Verify that all the values are okay, compute the size of the values, and
17052 // reverse the list.
17053 unsigned NumNegativeBits = 0;
17054 unsigned NumPositiveBits = 0;
17055
17056 // Keep track of whether all elements have type int.
17057 bool AllElementsInt = true;
17058
17059 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17060 EnumConstantDecl *ECD =
17061 cast_or_null<EnumConstantDecl>(Elements[i]);
17062 if (!ECD) continue; // Already issued a diagnostic.
17063
17064 const llvm::APSInt &InitVal = ECD->getInitVal();
17065
17066 // Keep track of the size of positive and negative values.
17067 if (InitVal.isUnsigned() || InitVal.isNonNegative())
17068 NumPositiveBits = std::max(NumPositiveBits,
17069 (unsigned)InitVal.getActiveBits());
17070 else
17071 NumNegativeBits = std::max(NumNegativeBits,
17072 (unsigned)InitVal.getMinSignedBits());
17073
17074 // Keep track of whether every enum element has type int (very common).
17075 if (AllElementsInt)
17076 AllElementsInt = ECD->getType() == Context.IntTy;
17077 }
17078
17079 // Figure out the type that should be used for this enum.
17080 QualType BestType;
17081 unsigned BestWidth;
17082
17083 // C++0x N3000 [conv.prom]p3:
17084 // An rvalue of an unscoped enumeration type whose underlying
17085 // type is not fixed can be converted to an rvalue of the first
17086 // of the following types that can represent all the values of
17087 // the enumeration: int, unsigned int, long int, unsigned long
17088 // int, long long int, or unsigned long long int.
17089 // C99 6.4.4.3p2:
17090 // An identifier declared as an enumeration constant has type int.
17091 // The C99 rule is modified by a gcc extension
17092 QualType BestPromotionType;
17093
17094 bool Packed = Enum->hasAttr<PackedAttr>();
17095 // -fshort-enums is the equivalent to specifying the packed attribute on all
17096 // enum definitions.
17097 if (LangOpts.ShortEnums)
17098 Packed = true;
17099
17100 // If the enum already has a type because it is fixed or dictated by the
17101 // target, promote that type instead of analyzing the enumerators.
17102 if (Enum->isComplete()) {
17103 BestType = Enum->getIntegerType();
17104 if (BestType->isPromotableIntegerType())
17105 BestPromotionType = Context.getPromotedIntegerType(BestType);
17106 else
17107 BestPromotionType = BestType;
17108
17109 BestWidth = Context.getIntWidth(BestType);
17110 }
17111 else if (NumNegativeBits) {
17112 // If there is a negative value, figure out the smallest integer type (of
17113 // int/long/longlong) that fits.
17114 // If it's packed, check also if it fits a char or a short.
17115 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17116 BestType = Context.SignedCharTy;
17117 BestWidth = CharWidth;
17118 } else if (Packed && NumNegativeBits <= ShortWidth &&
17119 NumPositiveBits < ShortWidth) {
17120 BestType = Context.ShortTy;
17121 BestWidth = ShortWidth;
17122 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17123 BestType = Context.IntTy;
17124 BestWidth = IntWidth;
17125 } else {
17126 BestWidth = Context.getTargetInfo().getLongWidth();
17127
17128 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17129 BestType = Context.LongTy;
17130 } else {
17131 BestWidth = Context.getTargetInfo().getLongLongWidth();
17132
17133 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17134 Diag(Enum->getLocation(), diag::ext_enum_too_large);
17135 BestType = Context.LongLongTy;
17136 }
17137 }
17138 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17139 } else {
17140 // If there is no negative value, figure out the smallest type that fits
17141 // all of the enumerator values.
17142 // If it's packed, check also if it fits a char or a short.
17143 if (Packed && NumPositiveBits <= CharWidth) {
17144 BestType = Context.UnsignedCharTy;
17145 BestPromotionType = Context.IntTy;
17146 BestWidth = CharWidth;
17147 } else if (Packed && NumPositiveBits <= ShortWidth) {
17148 BestType = Context.UnsignedShortTy;
17149 BestPromotionType = Context.IntTy;
17150 BestWidth = ShortWidth;
17151 } else if (NumPositiveBits <= IntWidth) {
17152 BestType = Context.UnsignedIntTy;
17153 BestWidth = IntWidth;
17154 BestPromotionType
17155 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17156 ? Context.UnsignedIntTy : Context.IntTy;
17157 } else if (NumPositiveBits <=
17158 (BestWidth = Context.getTargetInfo().getLongWidth())) {
17159 BestType = Context.UnsignedLongTy;
17160 BestPromotionType
17161 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17162 ? Context.UnsignedLongTy : Context.LongTy;
17163 } else {
17164 BestWidth = Context.getTargetInfo().getLongLongWidth();
17165 assert(NumPositiveBits <= BestWidth &&
17166 "How could an initializer get larger than ULL?");
17167 BestType = Context.UnsignedLongLongTy;
17168 BestPromotionType
17169 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17170 ? Context.UnsignedLongLongTy : Context.LongLongTy;
17171 }
17172 }
17173
17174 // Loop over all of the enumerator constants, changing their types to match
17175 // the type of the enum if needed.
17176 for (auto *D : Elements) {
17177 auto *ECD = cast_or_null<EnumConstantDecl>(D);
17178 if (!ECD) continue; // Already issued a diagnostic.
17179
17180 // Standard C says the enumerators have int type, but we allow, as an
17181 // extension, the enumerators to be larger than int size. If each
17182 // enumerator value fits in an int, type it as an int, otherwise type it the
17183 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
17184 // that X has type 'int', not 'unsigned'.
17185
17186 // Determine whether the value fits into an int.
17187 llvm::APSInt InitVal = ECD->getInitVal();
17188
17189 // If it fits into an integer type, force it. Otherwise force it to match
17190 // the enum decl type.
17191 QualType NewTy;
17192 unsigned NewWidth;
17193 bool NewSign;
17194 if (!getLangOpts().CPlusPlus &&
17195 !Enum->isFixed() &&
17196 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17197 NewTy = Context.IntTy;
17198 NewWidth = IntWidth;
17199 NewSign = true;
17200 } else if (ECD->getType() == BestType) {
17201 // Already the right type!
17202 if (getLangOpts().CPlusPlus)
17203 // C++ [dcl.enum]p4: Following the closing brace of an
17204 // enum-specifier, each enumerator has the type of its
17205 // enumeration.
17206 ECD->setType(EnumType);
17207 continue;
17208 } else {
17209 NewTy = BestType;
17210 NewWidth = BestWidth;
17211 NewSign = BestType->isSignedIntegerOrEnumerationType();
17212 }
17213
17214 // Adjust the APSInt value.
17215 InitVal = InitVal.extOrTrunc(NewWidth);
17216 InitVal.setIsSigned(NewSign);
17217 ECD->setInitVal(InitVal);
17218
17219 // Adjust the Expr initializer and type.
17220 if (ECD->getInitExpr() &&
17221 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17222 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17223 CK_IntegralCast,
17224 ECD->getInitExpr(),
17225 /*base paths*/ nullptr,
17226 VK_RValue));
17227 if (getLangOpts().CPlusPlus)
17228 // C++ [dcl.enum]p4: Following the closing brace of an
17229 // enum-specifier, each enumerator has the type of its
17230 // enumeration.
17231 ECD->setType(EnumType);
17232 else
17233 ECD->setType(NewTy);
17234 }
17235
17236 Enum->completeDefinition(BestType, BestPromotionType,
17237 NumPositiveBits, NumNegativeBits);
17238
17239 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17240
17241 if (Enum->isClosedFlag()) {
17242 for (Decl *D : Elements) {
17243 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17244 if (!ECD) continue; // Already issued a diagnostic.
17245
17246 llvm::APSInt InitVal = ECD->getInitVal();
17247 if (InitVal != 0 && !InitVal.isPowerOf2() &&
17248 !IsValueInFlagEnum(Enum, InitVal, true))
17249 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17250 << ECD << Enum;
17251 }
17252 }
17253
17254 // Now that the enum type is defined, ensure it's not been underaligned.
17255 if (Enum->hasAttrs())
17256 CheckAlignasUnderalignment(Enum);
17257}
17258
17259Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17260 SourceLocation StartLoc,
17261 SourceLocation EndLoc) {
17262 StringLiteral *AsmString = cast<StringLiteral>(expr);
17263
17264 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17265 AsmString, StartLoc,
17266 EndLoc);
17267 CurContext->addDecl(New);
17268 return New;
17269}
17270
17271void Sema::ActOnPragmaOpaque(IdentifierInfo* TypeName,
17272 IdentifierInfo* KeyName,
17273 SourceLocation PragmaLoc,
17274 SourceLocation TypeLoc,
17275 SourceLocation KeyLoc) {
17276
17277 Decl *TD = LookupSingleName(TUScope, TypeName, TypeLoc, LookupOrdinaryName);
17278 TypedefDecl *TypeDecl = TD ? dyn_cast<TypedefDecl>(TD) : 0;
17279 // Check that this is a valid typedef of an opaque type
17280 if (!TypeDecl || !TypeDecl->getUnderlyingType()->isPointerType()) {
17281 Diag(TypeLoc, diag::err_pragma_opaque_invalid_type);
17282 return;
17283 }
17284
17285 Decl *KD = LookupSingleName(TUScope, KeyName, KeyLoc, LookupOrdinaryName);
17286 VarDecl *KeyDecl = KD ? dyn_cast<VarDecl>(KD) : 0;
17287
17288 if (!KeyDecl) {
17289 Diag(KeyLoc, diag::err_pragma_opaque_invalid_key);
17290 return;
17291 }
17292
17293 TypeDecl->setOpaqueKey(KeyDecl);
17294}
17295
17296void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17297 IdentifierInfo* AliasName,
17298 SourceLocation PragmaLoc,
17299 SourceLocation NameLoc,
17300 SourceLocation AliasNameLoc) {
17301 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17302 LookupOrdinaryName);
17303 AsmLabelAttr *Attr =
17304 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17305
17306 // If a declaration that:
17307 // 1) declares a function or a variable
17308 // 2) has external linkage
17309 // already exists, add a label attribute to it.
17310 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17311 if (isDeclExternC(PrevDecl))
17312 PrevDecl->addAttr(Attr);
17313 else
17314 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17315 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17316 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17317 } else
17318 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17319}
17320
17321void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17322 SourceLocation PragmaLoc,
17323 SourceLocation NameLoc) {
17324 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17325
17326 if (PrevDecl) {
17327 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17328 } else {
17329 (void)WeakUndeclaredIdentifiers.insert(
17330 std::pair<IdentifierInfo*,WeakInfo>
17331 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17332 }
17333}
17334
17335void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17336 IdentifierInfo* AliasName,
17337 SourceLocation PragmaLoc,
17338 SourceLocation NameLoc,
17339 SourceLocation AliasNameLoc) {
17340 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17341 LookupOrdinaryName);
17342 WeakInfo W = WeakInfo(Name, NameLoc);
17343
17344 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17345 if (!PrevDecl->hasAttr<AliasAttr>())
17346 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17347 DeclApplyPragmaWeak(TUScope, ND, W);
17348 } else {
17349 (void)WeakUndeclaredIdentifiers.insert(
17350 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17351 }
17352}
17353
17354Decl *Sema::getObjCDeclContext() const {
17355 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17356}
17357